settings for simple global variables
1, the direct definition of global variable through VAR, this pure JS is the same.
2, use ANGULARJS value to set the global variable.
3, use ANGULARJS constant to set global variables.
The example code is as follows: In the app file, declare three kinds of variables
' Use strict ';
/* APP Module *
/var test2 = ' Tank '; Method 1, define global variable
var phonecatapp = angular.module (' Phonecatapp ', [ //define a Ng-app
' Ngroute ',
' Phonecatcontrollers ',
' tanktest '
]);
Phonecatapp.value (' test ', {"Test": "test222", "test1": "test111"}); Method 2 defines the global variable
phonecatapp.constant (' constanttest ', ' This is Constanttest '); Method 3 defines global variables
To read a global variable in controller
' Use strict ';
/* Controllers
/var phonecatcontrollers = angular.module (' Phonecatcontrollers ', []);
Phonecatcontrollers.controller (' Phonelistctrl ', [' $scope ', ' Test ', ' constanttest ',
function ($scope, test, Constanttest) {
$scope. test = test; Method 2, the global variable is assigned to the $scope.test
$scope. constanttest = constanttest; Method 3, Assignment
$scope. test2 = test2; Method 1, Assignment
}]);
Attention Matters
The Var test, when set, does not need to be injected into the controller declaration, and can be used directly. Value and Contant, which are initialized in the app, need to be injected into the controller in the Controller declaration before they can be used.
One problem with all three approaches is that you can only read global variables and cannot make modifications to global variables. Inability to meet business requirements in very business logic.
implement global variables using provider.
The steps are similar to the value and contant above. Complete the Declaration and initialization in the app.
<script type= "Text/javascript" >
var app = Angular.module (' NGROUTEWXCTB ', [' Ngroute ', ' ngcookies ']);
Todo:provider of globle uid and weixinisinit param
app.provider (' UserService ', function () {
var data = {Uid:0,w Eixinisinit:false};
var f = function (Uid,weixinisinit) {
if (UID!= 0)
{
data.uid= uid;
Data.weixinisinit = Weixinisinit;
}
return data;
this. $get = function () {return
F;};
});
</script>
At the time of Controller declaration, inject.
App.controller (' MyCtrl1 ', function ($scope, userservice) {
var data = userservice (0, 0, false);//Read global variable
}));
App.controller (' MyCtrl2 ', function ($scope, userservice) {
var data = UserService (123,, true);/set global variable
}));
The fetch and assignment of the parameters are realized through the Get method provided by provider.
Attention Matters
In the code, we designed the provider assignment operation, when the first parameter equals 0, the default is read, when the first parameter is not 0, the implementation is set to read. This way, you can have a common get method without adding new methods.