角度根范围更新

时间:2014-03-07 19:26:19

标签: javascript angularjs

我有一个页面,其中包含登录用户的“状态”部分,其中显示“欢迎,[名称]”,如果确实已登录,则会显示“注销”链接。

我正在尝试通过在LoginController上设置$ rootScope上的值来登录它们,并希望“状态”部分更改,但没有任何反应。我安装了Chrome扩展程序,我发现$rootScope.loggedIn确实设置为true

angular.module('pipelineChromeApp')
.controller('LoginController', [
'$rootScope',
'$scope',
'Profile',
'$location',
function ($rootScope, $scope, Profile, $location) {
  $scope.apiKey = '';
  $scope.error = '';


  $scope.login = function(){
    $scope.error = '';

    var login = Profile.getProfile($scope.apiKey)

    login.then(function(resp){

      $rootScope.loggedIn = true;
      $rootScope.name = resp.data.first_name;
      $rootScope.apiKey = resp.data.api_key;
      $rootScope.avatar = resp.data.avatar_thumb_url;

      // Sets data in localstorage
      Profile.login(resp.data);

      $location.path( "/actions" );

    }, function(error) {
      $scope.error = error.data.error;

    });
  };
}]);


angular.module('pipelineChromeApp')
.controller('StatusController', [
'$rootScope',
'Profile',
'$scope',
'localStorageService',
function ($rootScope, Profile, $scope, localStorageService) {
  $scope.loggedIn = $rootScope.loggedIn;
  $scope.name = $rootScope.name;

  $scope.logout = function() {
    Profile.logout()
    $location.path("/start");
  };

}]);

模板:

<div class="status" ng-controller="StatusController">
  <div ng-if="loggedIn">
    Welcome, <span ng-bind="name"></span>!
    <a href="#" ng-click="logout()">Logout</a>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

看起来我必须在$rootScope中使用$ watch来更新本地$scope