虽然正在设置数据,但AngularJS视图没有反映$ scope.model

时间:2014-05-06 07:09:37

标签: angularjs angularjs-scope authentication persistent-storage

非常感谢您阅读我的问题:)

目标:如果他们打开新标签页或刷新,我希望保留已登录用户的姓名和照片。最初进行身份验证(在表单提交时调用attempt.login)时,视图更新正常(如下所示:)

userController.js.coffee:

$scope.attemptLogin = ->
  $scope.showLoginForm = false
  $http.post(apiURL + "/login"
    email: $scope.credentials.email
    password: $scope.credentials.password
  ).success (data) ->
    if data.error
      console.log "error: " + data.error
    else
      $scope.user = data
      localStorageService.add("user", data)

问题是当我执行页面加载并尝试从本地存储变量设置$scope.user时(如此:)我看到console.log $scope.user就好了,但视图不反映任何用户数据。

userController.js.coffee:

$timeout ->
  if localStorageService.get("user") == undefined
    $scope.user = {}
    $scope.loggedIn = false
    console.log "no user"
  else
    $scope.user = localStorageService.get("user")
    console.log $scope.user
    $scope.$digest()
, 1

正如您所看到的,我已尝试将其置于$timeout块中以强制在下一个摘要中进行更改,甚至明确调用$scope.$digest()。我不知道我在哪里出错了,我已经在其他地方徘徊,显然无济于事。非常感谢任何有关此事的清醒!

的index.html:

<div class="login-signup" ng-cloak ng-controller="userController">
  <div class="user-details" id="user_details" ng-click="toggleUserMenu()" ng-show="loggedIn">
    <div>
      <img class="user-avatar-small" ng-model="user.photo_url" ng-src="{{user.photo_url}}">
      <div class="user-name" ng-model="user.name">
        {{user.name}}
      </div>
    </div>
  </div>
  <div class="user-menu" ng-show="loggedIn && showUserMenu">
    <a href ng-click="logOut()"> Log Out</a>
  </div>
  <a href ng-click="toggleLoginForm()" ng-show="!loggedIn && !showLoginForm" ng-cloak>Log In</a>
  <form class="form-inline" name="loginForm" ng-show="showLoginForm" ng-submit="attemptLogin()"ng-cloak>
    <span class="glyphicon glyphicon-remove-circle login-form-glyph" ng-click="toggleLoginForm()"></span>
    <label class="sr-only" for="email">email address</label>
    <input type="text" name="email" id="email" ng-model="credentials.email" placeholder="email" class="form-control"/>
    <br/>
    <label class="sr-only" for="password">password</label>
    <input type ="password" name="password" id="password" ng-model="credentials.password" placeholder="password" class="form-control"/>
    <br/>
    <input class="form-control" type="submit">
  </form>
</div>

2 个答案:

答案 0 :(得分:2)

视图可能看不到$scope.user的变化。尝试像这样包装else分支:

$scope.$apply(function(){
    $scope.user = data
    localStorageService.add("user", data)
})

这将强制更新手表和摘要周期。我不确定你的手动digest电话,但你应该避免这样称呼。

此外,您可以将用户称为http用户,而不是使用低级别resource;通过这种方式,Angular将返回一个承诺,并在收到数据时为您自动更新视图。

See also: resource docs

答案 1 :(得分:1)

在angularjs和更新视图的任何奇怪情况下 - 总是尝试:

$scope.$apply(function(){
   $scope.your_model = your_value;
});