AngularJS:在资源加载之前不要删除数据

时间:2014-07-24 18:59:57

标签: angularjs angularjs-service angularjs-resource

我对$resource完全不熟悉,所以我不确定如何使用它。

(这不是真正的代码,但它是相似的)

服务:

.factory('User', function ($resource) {
            return $resource(apiPath + 'user/:id', {}, {
                query: {method: 'GET', isArray: true}
            })
        })

控制器:

$scope.showUser = function(userID){
    $scope.user = User.get({id:userID});
}

视图:

<button ng-click="showUser(user.id+1)">Show user</button>

<h1>{{user.name}}</h1>

效果很好,但每次按下按钮时,用户的名称都会消失,然后在返回数据时显示 - $scope.user变为空,直到下一个用户加载为止。我不希望这样,我希望旧用户保持到下一个用户加载为止。感谢。

1 个答案:

答案 0 :(得分:2)

您可以指定一个回调函数,该函数将在获取资源时执行。

 // Not assigning the return value here on the scope ...

 User.get({ id: userID}, function(user) {

      // ... but rather here when the call has completed.

      $scope.user = user;

 });

有关详细信息,请参阅$resource documentation