angularjs全局变量 html文件,angularjs 设置全局变量的7种方法

在ng-app或控制器中定义的全局变量,在不一样的controller里均可以使用。html

1,经过var 直接定义global variable,这根纯js是同样的。jquery

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

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

4,用angularjs rootscope来设置全局变量 。ide

五、定义服务。this

六、$rootScope。spa

七、定义一个服务 来传 值:code

不一样controller之间传值,profile是自定义的一个服务!htm

.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种方法:blog

实例:

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,赋值

}]);

三、结果

{{test.test1}}

{{constanttest}}

{{test2}}

结果:test111 this is constanttest tank

其实咱们能够经过其余方法来实现全局变量,例如:angularjs factory的功能。

参考:http://blog.51yip.com/jsjquery/1601.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值