shacker
shacker

Reputation: 15371

Angular: Push, then delete an item

Use case: A user creates a new task, which has to be sent upstream through an API. When that API returns success, I add it to the scope for display. I have that working fine with:

$http.post('some_url', newtask).success(function(data) {
  $scope.tasks.push(data);
});

(newtask is a simple object defined earlier, not shown here).

The problem is, the API is quite slow (though reliable), whereas I want this to feel like a real-time app. So I'd like to push the new task to the $scope immediately, then replace it with the "real" one when the API returns success. So I prepend the above with:

$scope.tasks.push(newtask); // Add to UI immediately (provisionally)

What happens now is that the new task is added immediately, then a second copy of the task is added when the API returns. So what I'd like to do is remove the first copy as soon as the second copy is added.

I can't seem to find a find a way to do that. Or is my approach all wrong? (I admit, the approach does feel like a bit of a hack, so I'm open to suggestions).

Upvotes: 3

Views: 10079

Answers (2)

Umesh Kolapkar
Umesh Kolapkar

Reputation: 22

//Push the new task immediately
$scope.tasks.push(newtask);

//When API return check for error if error just pop out the added task
$http.post('some_url', newtask).success(function(data) {
    if($scope.tasks[$scope.tasks.length-1] !== data) {
        $scope.tasks.pop();
    } 
});

Upvotes: 0

Mark Rajcok
Mark Rajcok

Reputation: 364697

In the success callback function, I suggest you compare the new task (coming back from the API) to the last task in your tasks array. If they match, you don't have to do anything. (If they don't match, you'll need to remove the last item and throw up some kind of error indication.)

$http.post('some_url', newtask).success(function(data) {
   if($scope.tasks[$scope.tasks.length-1] === data) {
      // do nothing, we already added it before
   } else {
     ... error handling here
   }
});

If the user can't add more than one task at a time (before the API returns), and you really want to remove then add, just use normal JavaScript operations on the array to remove the last item, then add the API value:

$http.post('some_url', newtask).success(function(data) {
    $scope.tasks.pop();
    $scope.tasks.push(data);
});

Angular should notice the model change and automatically update the view for you.

Upvotes: 2

Related Questions