在AngularJS全局变量 [英] Global variables in AngularJS

查看:220
本文介绍了在AngularJS全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在那里我在一个控制范围内初始化的变量的问题。然后,它在其它控制器得到改变,当用户登录。使用这个变量来控制的东西,如导航栏和限制访问取决于用户类型网站的部分,所以它的重要的是,它拥有它的价值。它的问题是,它初始化控制器,得到由棱角分明一些再怎么叫,然后重置变回其初始值。

我想这是不是声明和初始化的全局变量的正确方法,以及它不是一个真正全球性的,所以我的问题是什么是正确的做法,是有办法解决的工作的很好的例子有角的当前版本<? / p>

解决方案

您已经有了基本的全局变量2个选项:

$ rootScope 是所有范围的父母因此暴露值会出现在所有模板和控制器可见。使用 $ rootScope 是很容易的,你可以简单地把它注射到任何控制器,并在此范围内更改值。这可能是方便,但有href=\"http://c2.com/cgi/wiki?GlobalVariablesAreBad\">全局变量的问题的所有

服务是可以注入到任何控制器和一个控制器的范围,暴露自己的价值观单身。服务,是单身还是'全球',但你有更好的控制,其中那些使用和暴露出来。

使用服务的复杂一点,但不算多,这里有一个例子:

  VAR对myApp = angular.module('对myApp',[]);
myApp.factory('UserService',函数(){
  返回{
      名称:匿名
  };
});

和然后在控制器:

 函数MyCtrl($范围,UserService){
    $ scope.name = UserService.name;
}

下面是工作的jsfiddle:<一href=\"http://jsfiddle.net/pkozlowski_opensource/BRWPM/2/\">http://jsfiddle.net/pkozlowski_opensource/BRWPM/2/

I have a problem where i'm initialising a variable on the scope in a controller. Then it gets changed in another controller when a user logs in. This variable is used to control things such as the navigation bar and restricts access to parts of the site depending on the type of user, so its important that it holds its value. The problem with it is that the controller that initialises it, gets called again by angular some how and then resets the variable back to its initial value.

I assume this is not the correct way of declaring and initialising global variables, well its not really global, so my question is what is the correct way and is there any good examples around that work with the current version of angular?

解决方案

You've got basically 2 options for "global" variables:

$rootScope is a parent of all scopes so values exposed there will be visible in all templates and controllers. Using the $rootScope is very easy as you can simply inject it into any controller and change values in this scope. It might be convenient but has all the problems of global variables.

Services are singletons that you can inject to any controller and expose their values in a controller's scope. Services, being singletons are still 'global' but you've got far better control over where those are used and exposed.

Using services is a bit more complex, but not that much, here is an example:

var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
  return {
      name : 'anonymous'
  };
});

and then in a controller:

function MyCtrl($scope, UserService) {
    $scope.name = UserService.name;
}

Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/BRWPM/2/

这篇关于在AngularJS全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆