在if / else语句内部工作时绑定到范围

时间:2015-04-23 19:59:11

标签: angularjs angularjs-scope

在我的控制器内,我有:

$scope.friends = userService.data.user.friends

但是,如果usernull,我显然会收到错误,因为无法访问userService.data.user.friends

所以,现在我使用:

if(userService.data.user){
    $scope.friends = userService.data.user.friends;
}else{
     $scope.friends = null;
}

问题是: if statement未绑定到$scope,因此仅评估once。因此,如果userService.data.user初始为null $scope.friends也会评估为nullbut stays null even if friends are added to userService.data.user later on(例如,按$ http请求)

我需要重新加载路线才能获得userService.data.user.friends的新值。

我如何将范围绑定到userService.data.user.friends,还处理null个案?

1 个答案:

答案 0 :(得分:0)

服务$ parse - https://docs.angularjs.org/api/ng/service/$parse



angular.module('app', [])
.controller('ctrl', function($scope, $parse, userService) {
  $scope.friends = $parse('data.user.friends')(userService)
  $scope.someDeepProperty = $parse('data.user.friends.data.deep')(userService) || 'we are so deep';
})
.factory('userService', function($timeout) {
  var userService = {}
  
  userService.data = {
    user: {
      friends: []
    }
  }
  
  $timeout(function() {
    userService.data.user.friends.push({name: 'foo'})
  }, 2000);
  
  return userService;
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app'>
  <div ng-controller='ctrl'>
    Friends: {{ friends }} - wait 2 seconds for update <br>
    Deep property: {{ someDeepProperty }}
  </div>
</div>
&#13;
&#13;
&#13;