Angularjs three ways to set global variables
Angularjs has two of its own, set the global variable method, in addition to JS set the global variable method, a total of three kinds. The function to implement is that global variables defined in Ng-app can be used in different ng-controller.
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.
Here is an example to illustrate the above 3 methods:
Instance:
1, in the app module, define global 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 the global variable
phonecatapp.config ([' $routeProvider ', //Set routing
function ($routeProvider) {
$ Routeprovider.
When ('/phones ', {
templateurl: ' partials/phone-list.html ' //Here is not set controller, you can add Ng-controller to the module
}).
When ('/phones/:p Honeid ', {
templateurl: ' partials/phone-detail.html ',
controller: ' Phonedetailctrl '
}).
When ('/login ', {
templateurl: ' partials/login.html ',
controller: ' Loginctrl '
}).
Otherwise ({
redirectto: '/login '
});
}];
2, calling global variables 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
}]);
3, look at the effect in HTML
<div data-ng-controller= "Phonelistctrl" >
{{test.test1}
} {{constanttest}}} </div>
Result: test111 This is Constanttest tank
In fact, we can implement global variables in other ways, such as: Angularjs factory function.
Thank you for reading, I hope to help you, thank you for your support for this site!