Angularjs 设置全局变量的方法总结
2016-10-20 15:53
776 查看
AngularJS 设置全局变量的三种方法
angularjs自身有二种,设置全局变量的方法,在加上js的设置全局变量的方法,总共有三种。要实现的功能是,在ng-app中定义的全局变量,在不同的ng-controller里都可以使用。
1,通过var 直接定义global variable,这根纯js是一样的。
2,用angularjs value来设置全局变量 。
3,用angularjs constant来设置全局变量 。
下面用一个例子,来说明,上面3种方法:
实例:
1,在app模块中,定义全局变量
'use strict'; /* App Module */ var test2 = 'tank'; //方法1,定义全局变量 var phonecatApp = angular.module('phonecatApp', [ //定义一个ng-app 'ngRoute', 'phonecatControllers', 'tanktest' ]); phonecatApp.value('test',{"test":"test222","test1":"test111"}); //方法2定义全局变量 phonecatApp.constant('constanttest', 'this is constanttest'); //方法3定义全局变量 phonecatApp.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中调用全局变量
'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,赋值 }]);
3,在html中看一下效果
<div data-ng-controller="PhoneListCtrl"> {{test.test1}} {{constanttest}} {{test2}} </div>
结果:test111 this is constanttest tank
其实我们可以通过其他方法来实现全局变量,例如:angularjs factory的功能。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
您可能感兴趣的文章:
- AngularJS之自定义服务详解(factory、service、provider)
- angularJS Provider、factory、service详解及实例代码
- Angularjs全局变量被作用域监听的正确姿势
- AngularJS中如何使用$parse或$eval在运行时对Scope变量赋值
- AngularJS内置指令
- AngularJS入门教程之学习环境搭建
- AngularJS实现元素显示和隐藏的几个案例
- angularJS中router的使用指南
- AngularJS实现表单验证
- angularjs 处理多个异步请求方法汇总
- AngularJS中的指令全面解析(必看)
- AngularJS基于provider实现全局变量的读取和赋值方法
相关文章推荐
- angularJs设置全局变量的N种方法
- angularjs 设置全局变量的3种方法
- angularjs 设置全局变量的3种方法
- angularjs 设置全局变量的7种方法
- angularjs 设置全局变量的7种方法
- Ionic 跨平台开发之AngularJS全局变量设置的三种方法
- angularjs 设置全局变量的7种方法
- angularjs 设置全局变量的方法
- [转]angularjs 设置全局变量的3种方法
- angularjs 设置全局变量的3种方法
- Angularjs 设置全局变量的3种方法
- ASP.Net全局变量的设置和读取方法
- linux环境变量设置方法总结(PATH/LD_LIBRARY_PATH)
- Linux 设置全局环境变量的三种方法
- ASP.Net全局变量的设置和读取方法
- 在BSP的.bat文件下设置全局变量的方法
- ASP.Net下两种全局变量的设置和读取方法
- ASP.Net全局变量的设置和读取方法
- 【新版】VC中全局变量的使用总结(N种方法,看完就不再疑惑啦!)
- ASP.Net下两种全局变量的设置和读取方法