Angularjs method for setting global variables summary, angularjs global variables
Three methods for setting global variables in AngularJS
Angularjs has two ways to set global variables. In addition, there are three methods to set global variables in js. The function to be implemented is that global variables defined in ng-app can be used in different ng-controllers.
1. Use var to directly define global variable. This pure js is the same.
2. Use angularjs value to set global variables.
3. Use angularjs constant to set global variables.
The following uses an example to describe the above three methods:
Instance:
1. Define global variables in the app Module
'Use strict ';/* App Module */var test2 = 'tank'; // method 1, define the global variable var phonecatApp = angular. module ('phonecatapp', [// define an ng-app 'ngroup', 'pythonecatcontrollers', '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 the routing function ($ routeProvider) {$ routeProvider. when ('/phones', {templateUrl: 'partials/phone-list.html '// No controller is set here, you can add ng-controller} in the module }). when ('/phones/: phoneid', {templateUrl: 'partials/phone-detail.html', controller: 'phonedetailctrl '}). when ('/login', {templateUrl: 'partials/login.html', controller: 'loginctrl '}). otherwise ({redirectTo: '/login'}) ;}]);
2. Call global variables in controller
'Use strict ';/* Controllers */var phonecatControllers = angular. module ('pythonecatcontrollers', []); phonecatControllers. controller ('pythonelistctrl ', [' $ scope ', 'test', 'constanttest', function ($ scope, test, constanttest) {$ scope. test = test; // method 2. Assign the global variable to $ scope. test $ scope. constanttest = constanttest; // method 3, assigned $ scope. test2 = test2; // method 1, value assignment}]);
3. Check the effect in html.
<div data-ng-controller="PhoneListCtrl"> {{test.test1}} {{constanttest}} {{test2}}</div>
Result: test111 this is constanttest tank.
In fact, we can use other methods to implement global variables, such as the angularjs factory function.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!