angularjs 設定全域變數的3種方法

來源:互聯網
上載者:User

標籤:

angularjs自身有二種,設定全域變數的方法,在加上js的設定全域變數的方法,總共有三種。要實現的功能是,在ng-app中定義的全域變數,在不同的ng-controller裡都可以使用。

1,通過var 直接定義global variable,這根純js是一樣的。

2,用angularjs value來設定全域變數 。

3,用angularjs constant來設定全域變數 。

下面用一個例子,來說明,上面3種方法:

 

執行個體:

1,在app模組中,定義全域變數

查看複製列印?
  1. ‘use strict‘;  
  2.   
  3. /* App Module */  
  4.   
  5. var test2 = ‘tank‘;         //方法1,定義全域變數  
  6.   
  7. var phonecatApp = angular.module(‘phonecatApp‘, [     //定義一個ng-app  
  8.   ‘ngRoute‘,  
  9.   ‘phonecatControllers‘,  
  10.   ‘tanktest‘  
  11. ]);  
  12.   
  13. phonecatApp.value(‘test‘,{"test":"test222","test1":"test111"});  //方法2定義全域變數  
  14.   
  15. phonecatApp.constant(‘constanttest‘, ‘this is constanttest‘);    //方法3定義全域變數  
  16.   
  17. phonecatApp.config([‘$routeProvider‘,                //設定路由  
  18.   function($routeProvider) {  
  19.     $routeProvider.  
  20.       when(‘/phones‘, {  
  21.         templateUrl: ‘partials/phone-list.html‘      //這裡沒有設定controller,可以在模組中加上ng-controller  
  22.       }).  
  23.       when(‘/phones/:phoneId‘, {  
  24.         templateUrl: ‘partials/phone-detail.html‘,  
  25.         controller: ‘PhoneDetailCtrl‘  
  26.       }).  
  27.       when(‘/login‘, {  
  28.         templateUrl: ‘partials/login.html‘,  
  29.         controller: ‘loginctrl‘  
  30.       }).  
  31.       otherwise({  
  32.         redirectTo: ‘/login‘  
  33.       });  
  34.   }]);  

2,在controller中調用全域變數

查看複製列印?
  1. ‘use strict‘;  
  2.   
  3. /* Controllers */  
  4.   
  5. var phonecatControllers = angular.module(‘phonecatControllers‘, []);  
  6.   
  7. phonecatControllers.controller(‘PhoneListCtrl‘, [‘$scope‘,‘test‘,‘constanttest‘,  
  8.   function($scope,test,constanttest) {  
  9.     $scope.test = test;                   //方法2,將全域變數賦值給$scope.test  
  10.     $scope.constanttest = constanttest;   //方法3,賦值  
  11.     $scope.test2 = test2;                 //方法1,賦值  
  12.   }]);  

3,在html中看一下效果

查看複製列印?
  1. <div data-ng-controller="PhoneListCtrl">  
  2.     {{test.test1}}  
  3.     {{constanttest}}  
  4.     {{test2}}  
  5. </div>  
  6.   
  7. 結果:test111 this is constanttest tank  

其實我們可以通過其他方法來實現全域變數,例如:angularjs factory的功能。

83

地址:http://blog.51yip.com/jsjquery/1601.html

angularjs 設定全域變數的3種方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.