There are two kinds of Angularjs itself, the method of setting global variables, and the method of setting global variables with js, there are altogether three KINDS. The function to be implemented is that the global variables defined in the Ng-app can be used in different ng-controller.
1, the direct definition of global variable by var, This pure JS is the Same.
2, set the global variable with ANGULARJS Value.
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
View Copy print?
- ' Use strict ';
- /* App Module */
- var test2 = ' Tank '; //method 1, Define global variables
- var Phonecatapp = angular.module (' Phonecatapp ', [ //define a Ng-app
- ' Ngroute ',
- ' Phonecatcontrollers ',
- ' Tanktest '
- ]);
- Phonecatapp.value (' test ', {"test":"test222","test1":"test111"}); //method 2 Define global variables
- Phonecatapp.constant (' constanttest ', ' This is constanttest '); //method 3 Define global variables
- Phonecatapp.config ([' $routeProvider ', //set Route
- function ($routeProvider) {
- $routeProvider.
- When ('/phones ', {
- Templateurl: ' partials/phone-list.html ' //the controller is not set here and can be added to the module Ng-controller
- }).
- When ('/phones/:p honeid ', {
- Templateurl: ' partials/phone-detail.html ',
- Controller: ' Phonedetailctrl '
- }).
- When ('/login ', {
- Templateurl: ' partials/login.html ',
- Controller: ' Loginctrl '
- }).
- otherwise ({
- Redirectto: '/login '
- });
- }]);
2, calling the global variable in the controller
View Copy print?
- ' Use strict ';
- /* Controllers */
- var phonecatcontrollers = angular.module (' phonecatcontrollers ', []);
- Phonecatcontrollers.controller (' Phonelistctrl ', [' $scope ',' Test ', 'constanttest ',
- function ($scope, test,constanttest) {
- $scope. test = test; //method 2, Assign the global variable to $scope.test
- $scope. constanttest = constanttest; //method 3, Assignment
- $scope. test2 = test2; //method 1, Assignment
- }]);
3, look at the effect in HTML
View Copy print?
- <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: Angularjs factory Function.
83
Address: http://blog.51yip.com/jsjquery/1601.html
Angularjs 3 ways to set global variables