How to set global variables by angular
This article mainly explains "how to set global variables in angular". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to set global variables in angular.
There are two functions for setting global variables in angualr, which are injected in the form of defining services, constant () and value (). Let's take a look at the code:
Please click on me 1 `value1` Please click on me 2 `value2` var app = angular.module ('myApp', []); app.constant (' myConstant', {"value1": "", "value2": "hello world", value3:1}) App.controller ('myCtrl1', function ($scope,myConstant) {$scope.onclick1 = function () {$scope.value1 = myConstant.value1 + (+ + myConstant.value3);};}); app.controller (' myCtrl2', function ($scope,myConstant) {$scope.onclick2 = function () {$scope.value2 = myConstant.value2 + (+ + myConstant.value3);} ); Please click on me 1 `value1` Please click on me 2 `value2` var app = angular.module ('myApp', []); app.value (' myConstant', {"value1": "", "value2": "hello world", value3:1}) App.controller ('myCtrl1', function ($scope,myConstant) {$scope.onclick1 = function () {$scope.value1 = myConstant.value1 + (+ + myConstant.value3);};}); app.controller (' myCtrl2', function ($scope,myConstant) {$scope.onclick2 = function () {$scope.value2 = myConstant.value2 + (+ + myConstant.value3);} })
The results of the above two codes are the same, and value3 will increase with each click, which once again proves the ability of value and constant to set global variables. Someone asked that the results of the two codes are the same, so what's the difference?
The difference between the two is that value cannot be injected into config, but constant can.
App.constant ('myConstant', {"value1": "", "value2": "hello world", value3:1}); app.value (' myValue', {"value1": "", "value2": "hello world", value3:1}); app.config (function (myValue) {.. });
Running the above code will report an error.
App.config (function (myConstant) {/ / you can get the 'myConstant'}' defined by constant); now that you have a better understanding of "how to set global variables in angular", you might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!