標籤:
angularjs自身有二種,設定全域變數的方法,在加上js的設定全域變數的方法,總共有三種。要實現的功能是,在ng-app中定義的全域變數,在不同的ng-controller裡都可以使用。
1,通過var 直接定義global variable,這根純js是一樣的。
2,用angularjs value來設定全域變數 。
3,用angularjs constant來設定全域變數 。
下面用一個例子,來說明,上面3種方法:
執行個體:
1,在app模組中,定義全域變數
查看複製列印?
- ‘use strict‘;
-
- /* App Module */
-
- var test2 = ‘tank‘; //方法1,定義全域變數
-
- var phonecatApp = angular.module(‘phonecatApp‘, [ //定義一個ng-app
- ‘ngRoute‘,
- ‘phonecatControllers‘,
- ‘tanktest‘
- ]);
-
- phonecatApp.value(‘test‘,{"test":"test222","test1":"test111"}); //方法2定義全域變數
-
- phonecatApp.constant(‘constanttest‘, ‘this is constanttest‘); //方法3定義全域變數
-
- phonecatApp.config([‘$routeProvider‘, //設定路由
- function($routeProvider) {
- $routeProvider.
- when(‘/phones‘, {
- templateUrl: ‘partials/phone-list.html‘ //這裡沒有設定controller,可以在模組中加上ng-controller
- }).
- when(‘/phones/:phoneId‘, {
- templateUrl: ‘partials/phone-detail.html‘,
- controller: ‘PhoneDetailCtrl‘
- }).
- when(‘/login‘, {
- templateUrl: ‘partials/login.html‘,
- controller: ‘loginctrl‘
- }).
- otherwise({
- redirectTo: ‘/login‘
- });
- }]);
2,在controller中調用全域變數
查看複製列印?
- ‘use strict‘;
-
- /* Controllers */
-
- var phonecatControllers = angular.module(‘phonecatControllers‘, []);
-
- phonecatControllers.controller(‘PhoneListCtrl‘, [‘$scope‘,‘test‘,‘constanttest‘,
- function($scope,test,constanttest) {
- $scope.test = test; //方法2,將全域變數賦值給$scope.test
- $scope.constanttest = constanttest; //方法3,賦值
- $scope.test2 = test2; //方法1,賦值
- }]);
3,在html中看一下效果
查看複製列印?
- <div data-ng-controller="PhoneListCtrl">
- {{test.test1}}
- {{constanttest}}
- {{test2}}
- </div>
-
- 結果:test111 this is constanttest tank
其實我們可以通過其他方法來實現全域變數,例如:angularjs factory的功能。
83
地址:http://blog.51yip.com/jsjquery/1601.html
angularjs 設定全域變數的3種方法