2014-04-26 75 views
0

在我更新了angularjs中的用戶之後,我將使用新的userdata更新$ scope.user。一種方法是做一個新的API請求來獲取所有用戶。但我認爲,更好地更新$範圍。我發現$適用,但我不知道如何使用它。

app.controller('UserCtrl', function($scope, APIService) { 

    $scope.users = APIService.query({ route:'users' }); 

    $scope.activate = function(user) { 

     var updateUser = {}; 

     if(user.activated) { 

      updateUser.activated = false; 

     } else { 

      updateUser.activated = true; 

     } 

     APIService.update({ route:'users', id: user._id }, updateUser, function(updatedUser) { 


      //update $scope.users with new data from updatedUser; 

     }); 

    } 

}); 

的updatedUser看起來是這樣的:

{"__v":0,"_id":"535aa89d8b2766d012e14c21","activated":true,"role":"user","local":{"surname":"Carter","prename":"Rob","password":"459DS","email":"test"},"$promise":{},"$resolved":true} 

服務:

app.service("APIService", function($resource) { 

    return $resource('http://localhost:3000/api/:route/:id', { route: "@route", id: "@id" }, { 
     'update': { method: 'PUT' } 
    }); 

}); 
+0

我們可以看到'update'方法的服務代碼嗎?這似乎是你給這個方法一個回調,而不是AngularJS的'.then()'有承諾。 – kba

+0

當然,我更新了我的第一篇文章。在我使用的另一個項目中:angular.copy(updatedUser,$ scope.users [index]);你認爲那是一種選擇嗎? – nofear87

回答

1

如果您使用ngRoute使用:

$route.reload()

Causes $route service to reload the current route even if $location hasn't changed. 

As a result of that, ngView creates new scope, reinstantiates the controller. 

,如果你正在使用ui-router

$state.reload();

但是我想一個更好的辦法是重新召回了$資源調用:

var getUsers=function(){ 
    $scope.users = APIService.query({ route:'users' }); 
} 

你可以調用它最初喜歡此:

getUsers();

在你更新的回調:

APIService.update({ route:'users', id: user._id }, updateUser, function(updatedUser) { 
    getUsers(); 
}); 

編輯

我不知道你所說的「更新的範圍」是什麼意思?你的意思是再次運行控制器?在那種情況下,你再次進行新的API調用,就像調用我建議的getUsers()方法一樣。如果你的意思是你想用你的新數據更新你的$scope陣列,而不是再次調用服務器來獲取整個用戶,那麼在你更新方法的回調中可以這樣做:

angular.forEach($scope.users,function(user,key){ 
    if(user._id == updatedUser._id){ 
    $scope.users[key]=updatedUser; 
    } 
}) 
+0

謝謝!多數民衆贊成我的意思是我的API請求。但是也許有更好的方法來更新範圍而不是請求整個用戶數據。 – nofear87

+0

@ nofear87看到我的更新。 –