Global variables in AngularJS

前端 未结 12 1935
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 12:05

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 co

12条回答
  •  不要未来只要你来
    2020-11-22 12:08

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

    • use a $rootScope http://docs.angularjs.org/api/ng.$rootScope
    • use a service 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. 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/

提交回复
热议问题