在我的控制器内,我有:
$scope.friends = userService.data.user.friends
但是,如果user
为null
,我显然会收到错误,因为无法访问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
也会评估为null
,but stays null even if friends are added to
userService.data.user later on
(例如,按$ http请求)
我需要重新加载路线才能获得userService.data.user.friends
的新值。
我如何将范围绑定到userService.data.user.friends
,还处理null
个案?
答案 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;