`
hudeyong926
  • 浏览: 2016627 次
  • 来自: 武汉
社区版块
存档分类
最新评论

angularjs 设置全局变量的3种方法

 
阅读更多

angularjs自身有二种,设置全局变量的方法,在加上js的设置全局变量的方法,总共有三种。要实现的功能是,在ng-app中定义的全局变量,在不同的ng-controller里都可以使用。

1,通过var 直接定义global variable,这根纯js是一样的。

2,用angularjs value来设置全局变量 。

3,用angularjs constant来设置全局变量 。

下面用一个例子,来说明,上面3种方法:

'use strict';
/* App Module */
var test2 = 'tank';         //方法1,定义全局变量

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

phonecatApp.value('test',{"test":"test222","test1":"test111"});  //方法2定义全局变量

phonecatApp.constant('constanttest', 'this is constanttest');    //方法3定义全局变量

 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,赋值
  }]);

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

value vs. constant

$provide.value('pageCount', 7);
$provide.constant('pageCount', 7);

区别一:value可以被修改,constant一旦声明无法被修改

$provide.decorator('pageCount', function($delegate) {
    return $delegate + 1;
});

 decorator可以用来修改(修饰)已定义的provider们,除了constant

区别二:value不可在config里注入,constant可以

myApp.config(function(pageCount){
    //可以得到constant定义的'pageCount'
});

 关于config,之后会专门介绍

 

全局方法

var TestCtrl = function $scope,facetorytest,servicetest) {  
    $scope.facetorytest = facetorytest.firstname+" "+facetorytest.lastname();  
    $scope.servicetest = servicetest.firstname+" "+servicetest.lastname();  
} 

var searchAndShow = function($scope, $routeParams, $location) {
  show($scope, $routeParams);
  $scope.search = function(){
    $location.search($scope.searchData).replace();
  }
}

 啥地方萨芬

 
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics