user3127896
user3127896

Reputation: 6563

angular update scope's properties on view issue

I have following object in my scope with property status which is OPENED by default

$scope.task = {
     status: 'OPENED'
}

All i want to do is change this status on click. Here is a simple scenario how it should work. But in my real project request sends to server and changes status in database so it takes some time.

Basically it looks like this:

$scope.changeStatus = function (task, status) {
        task.status = status;
        task.$update();
    };

So when this method is invoked at first I change status in my $scope.task and it changes immediately on my view(thanks to bi-directional data binding) but two buttons appear at the same time as well. Then after a few milliseconds the second button gone. I am wondering what is the best way to fix it? Should i create a copy of scope object or is there other ways?

Upvotes: 0

Views: 83

Answers (1)

Itamar L.
Itamar L.

Reputation: 519

I assume you are using $resource for your $update() method. You can use the promise that the functions return.

It's worth noting that the success callback for get, query and other methods gets passed in the response that came from the server as well as $http header getter function

From $resource @ angularjs.org.

Example:

var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(u, getResponseHeaders){
  u.abc = true;
  u.$save(function(u, putResponseHeaders) {
    //u => saved user object
    //putResponseHeaders => $http header getter
  });
});

So in your case:

$scope.changeStatus = function (task, status) {
        task.status = status;
        task.$update(function() { $scope.task.status = status });
    };

Upvotes: 1

Related Questions