angular4设置全局变量_angularjs 设置全局变量的7种方法
在ng-app或控制器中定義的全局變量,在不同的controller里都可以使用。
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、結果
{{test.test1}}
{{constanttest}}
{{test2}}
結果:test111?this?is?constanttest?tank
其實我們可以通過其他方法來實現全局變量,例如:angularjs factory的功能。
參考:http://blog.51yip.com/jsjquery/1601.html
總結
以上是生活随笔為你收集整理的angular4设置全局变量_angularjs 设置全局变量的7种方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pg加密扩展的安装_postgresql
- 下一篇: 橙光游戏《东方赤雪》攻略