angularjs 设置全局变量的7种方法
2016-08-09 15:14
656 查看
在ng-app或控制器中定义的全局变量,在不同的controller里都可以使用。
1,通过var 直接定义global variable,这根纯js是一样的。
2,用angularjs value来设置全局变量 。
3,用angularjs constant来设置全局变量 。
4,用angularjs rootscope来设置全局变量 。
5、定义服务。
6、$rootScope。
7、定义一个服务 来传 值:
不同controller之间传值,profile是自定义的一个服务!
下面用一个例子,来说明其中3种方法:
实例:
1,在app模块中,定义全局变量:
2,在controller中调用全局变量
3、结果
其实我们可以通过其他方法来实现全局变量,例如:angularjs factory的功能。
源引:http://my.oschina.net/u/2395167/blog/520532?p={{totalPage}}
1,通过var 直接定义global variable,这根纯js是一样的。
2,用angularjs value来设置全局变量 。
3,用angularjs constant来设置全局变量 。
4,用angularjs rootscope来设置全局变量 。
5、定义服务。
6、$rootScope。
7、定义一个服务 来传 值:
不同controller之间传值,profile是自定义的一个服务!
.controller('a',function(){ Profile.userNameAll = $scope.user.userName; Profile.cellphone = $scope.user.phoneNum; })
.controller('b',function(){ $scope.userName = Profile.userNameAll; $scope.phoneNum = Profile.cellphone; })
下面用一个例子,来说明其中3种方法:
实例:
1,在app模块中,定义全局变量:
var test2 = 'tank'; //方法1,定义全局变量 var app = angular.module('app', [ 'ngRoute', 'phonecatControllers', 'tanktest' ]); app .value('test',{"test":"test222","test1":"test111"}); //方法2定义全局变量 app .constant('constanttest', 'this is constanttest'); //方法3定义全局变量 app .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中调用全局变量
/* 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、结果
<div data-ng-controller="PhoneListCtrl"> {{test.test1}} {{constanttest}} {{test2}} </div> 结果:test111 this is constanttest tank
其实我们可以通过其他方法来实现全局变量,例如:angularjs factory的功能。
源引:http://my.oschina.net/u/2395167/blog/520532?p={{totalPage}}
相关文章推荐
- angularjs 设置全局变量的7种方法
- angularjs 设置全局变量的7种方法
- angularjs 设置全局变量的方法
- Angularjs 设置全局变量的方法总结
- angularJs设置全局变量的N种方法
- [转]angularjs 设置全局变量的3种方法
- angularjs 设置全局变量的3种方法
- Ionic 跨平台开发之AngularJS全局变量设置的三种方法
- Angularjs 设置全局变量的3种方法
- angularjs 设置全局变量的3种方法
- angularjs 设置全局变量的3种方法
- ASP.Net全局变量的设置和读取方法--非常好的一篇文章!
- ASP.Net全局变量的设置和读取方法
- lua如何设置只读全局变量——通过元方法与环境
- ASP.Net全局变量的设置和读取方法
- Linux设置全局环境变量的三种方法
- ASP.Net全局变量的设置和读取方法
- 设置和读取ASP.Net全局变量的方法
- 在BSP的.bat文件下设置全局变量的方法
- ASP.Net全局变量的设置和读取方法