Global variables in AngularJS

前端 未结 12 1931
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  萌比男神i
    2020-11-22 12:13

    Example of AngularJS "global variables" using $rootScope:

    Controller 1 sets the global variable:

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

    Controller 2 reads the global variable:

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

    Here is a working jsFiddle: http://jsfiddle.net/natefriedman/3XT3F/1/

提交回复
热议问题