AngularJS中的全局变量

本文翻译自:Global variables in AngularJS

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? 我认为这不是声明和初始化全局变量的正确方法,它也不是真正的全局变量,所以我的问题是正确的方法是什么,在使用当前版本的angular时是否有很好的例子可以解决?


#1楼

参考:https://stackoom.com/question/o5iW/AngularJS中的全局变量


#2楼

You've got basically 2 options for "global" variables: 对于“全局”变量,您基本上有2个选项:

  • use a $rootScope http://docs.angularjs.org/api/ng.$rootScope 使用$rootScope http://docs.angularjs.org/api/ng.$ro​​otScope
  • use a service http://docs.angularjs.org/guide/services 使用服务http://docs.angularjs.org/guide/services

$rootScope is a parent of all scopes so values exposed there will be visible in all templates and controllers. $rootScope是所有作用域的父项,因此在那里公开的值将在所有模板和控制器中可见。 Using the $rootScope is very easy as you can simply inject it into any controller and change values in this scope. 使用$rootScope非常容易,因为您可以简单地将其注入任何控制器并更改该范围中的值。 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/ 这是工作中的jsFiddle: http : //jsfiddle.net/pkozlowski_opensource/BRWPM/2/


#3楼

Example of AngularJS "global variables" using $rootScope : 使用$rootScope的AngularJS“全局变量”示例:

Controller 1 sets the global variable: 控制器1设置全局变量:

function MyCtrl1($scope, $rootScope) {
    $rootScope.name = 'anonymous'; 
}

Controller 2 reads the global variable: 控制器2读取全局变量:

function MyCtrl2($scope, $rootScope) {
    $scope.name2 = $rootScope.name; 
}

Here is a working jsFiddle: http://jsfiddle.net/natefriedman/3XT3F/1/ 这是一个工作的jsFiddle: http : //jsfiddle.net/natefriedman/3XT3F/1/


#4楼

localStorage.username = 'blah'

If you're guaranteed to be on a modern browser. 如果可以保证您使用的是现代浏览器。 Though know your values will all be turned into strings. 虽然知道您的值都将变成字符串。

Also has the handy benefit of being cached between reloads. 还具有在重新加载之间进行缓存的便捷好处。


#5楼

If you just want to store a value, according to the Angular documentation on Providers , you should use the Value recipe: 如果只想存储值,则根据Providers上的Angular文档 ,应使用值配方:

var myApp = angular.module('myApp', []);
myApp.value('clientId', 'a12345654321x');

Then use it in a controller like this: 然后在像这样的控制器中使用它:

myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
    this.clientId = clientId;
}]);

The same thing can be achieved using a Provider, Factory, or Service since they are "just syntactic sugar on top of a provider recipe" but using Value will achieve what you want with minimal syntax. 使用提供者,工厂或服务可以实现相同的目的,因为它们“只是提供者配方之上的语法糖”,但是使用Value将以最小的语法实现您想要的结果。

The other option is to use $rootScope , but it's not really an option because you shouldn't use it for the same reasons you shouldn't use global variables in other languages. 另一个选择是使用$rootScope ,但这并不是真正的选择,因为出于相同的原因,您不应该使用它,而不应该使用其他语言的全局变量。 It's advised to be used sparingly. 建议谨慎使用。

Since all scopes inherit from $rootScope , if you have a variable $rootScope.data and someone forgets that data is already defined and creates $scope.data in a local scope you will run into problems. 由于所有作用域都继承自$rootScope ,如果您具有变量$rootScope.data ,但有人忘记了data已经定义,并在本地作用域中创建$scope.data ,则会遇到问题。


If you want to modify this value and have it persist across all your controllers, use an object and modify the properties keeping in mind Javascript is pass by "copy of a reference" : 如果要修改此值并使它在所有控制器中持久存在,请使用一个对象并修改属性,请记住,Javascript是通过“引用副本”传递的:

myApp.value('clientId', { value: 'a12345654321x' });
myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
    this.clientId = clientId;
    this.change = function(value) {
        clientId.value = 'something else';
    }
}];

JSFiddle example JSFiddle示例


#6楼

You can also do something like this .. 你也可以做这样的事..

function MyCtrl1($scope) {
    $rootScope.$root.name = 'anonymous'; 
}

function MyCtrl2($scope) {
    var name = $rootScope.$root.name;
}

你可能感兴趣的:(angularjs)