小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

angularjs 設(shè)置全局變量的3種方法?海底蒼鷹(tank)博客

 huhuwoo 2015-10-10

angularjs自身有二種,設(shè)置全局變量的方法,在加上js的設(shè)置全局變量的方法,總共有三種。要實(shí)現(xiàn)的功能是,在ng-app中定義的全局變量,在不同的ng-controller里都可以使用。

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

2,用angularjs value來設(shè)置全局變量 。

3,用angularjs constant來設(shè)置全局變量 。

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

實(shí)例:

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',                //設(shè)置路由  
  18.   function($routeProvider) {  
  19.     $routeProvider.  
  20.       when('/phones', {  
  21.         templateUrl: 'partials/phone-list.html'      //這里沒有設(shè)置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中調(diào)用全局變量

  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. 結(jié)果:test111 this is constanttest tank  

其實(shí)我們可以通過其他方法來實(shí)現(xiàn)全局變量,例如:angularjs factory的功能。

1

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多