【Ionic】AngularJS全局變量設置的三種方法

angularjs自身有二種設置全局變量的方法,再加上js的設置全局變量的方法,總共有三種。

要實現的功能是,在ng-app中定義的全局變量,在不同的ng-controller裏都可以使用。

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

    2,用angularjs value來設置全局變量 。

    3,用angularjs constant來設置全局變量 。

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

    設置全局變量

    /* App Module */    

    var test2 = 'tank';        //方法1,定義全局變量 

    var phonecatApp = angular.module('phonecatApp',[]);    

    phonecatApp.value('test',{"test":"test222","test1":"test111"});  

    //方法2定義全局變量

    phonecatApp.constant('constanttest', 'this isconstanttest');    

    //方法3定義全局變量    

    然後在controller中調用全局變量

    /* 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,賦值

    }]);

 

value只能注入controller,factory,service等,constant可以注入任何方法。

 

DONE

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章