如何在angularjs中手动更新$ scope

时间:2014-04-26 16:24:03

标签: angularjs

在我更新angularjs中的用户后,我将使用新的userdata更新$ scope.user。一种方法是执行新的api请求以获取所有用户。但我认为,最好更新$ scope。我发现$ apply,但我不知道如何使用它。

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' }
    });

});

1 个答案:

答案 0 :(得分: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();

但是我认为更好的方法是再次召回$ resource:

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;
  }
})