AngularJS 中的全局变量 [英] Global variables in AngularJS

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

问题描述

我在初始化控制器作用域上的变量时遇到问题.然后,当用户登录时,它会在另一个控制器中更改.此变量用于控制诸如导航栏之类的内容,并根据用户类型限制对站点部分的访问,因此保持其值很重要.它的问题在于初始化它的控制器,通过某种方式再次被角度调用,然后将变量重置回其初始值.

我认为这不是声明和初始化全局变量的正确方法,而且它并不是真正的全局变量,所以我的问题是正确的方法是什么,是否有任何很好的例子可以与当前版本的 angular 一起使用?

解决方案

全局"变量基本上有 2 个选项:

$rootScope 是所有范围的父级,因此在那里公开的值将在所有模板和控制器中可见.使用 $rootScope 非常简单,因为您可以简单地将其注入任何控制器并更改此范围内的值.它可能很方便,但具有所有全局变量的问题.

服务是单例,您可以将其注入任何控制器并在控制器的范围内公开它们的值.作为单例的服务仍然是全球性的",但您可以更好地控制这些服务的使用和公开位置.

使用服务有点复杂,但没那么复杂,下面是一个例子:

var myApp = angular.module('myApp',[]);myApp.factory('UserService', function() {返回 {名称:'匿名'};});

然后在控制器中:

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

这是正在运行的 jsFiddle: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天全站免登陆