Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular js revert change of scope property inside a watch statement

I have a select box that triggers an http PUT when it's changed.

html:

<select ng-model='color'></select>

js:

$scope.$watch('color', function(newValue, oldValue) { 
    $http.put('...', {color: newValue})   
});

The issue is that if the http request fails for whatever reason I want the select box to revert to it's previous value.

 $scope.$watch('color', function(newValue, oldValue) { 
    req = $http.put('...', {color: newValue})
    req.error(function(){
      $scope.color = oldValue  // will probably cause the $watch to get triggered again (bad)
    });   
});

This will probably cause the $watch function to get triggered again which is not desirable as it would trigger an unnecessary PUT.

How can I revert the value without triggering the $watch function again?

like image 945
Christian Schlensker Avatar asked Oct 23 '13 19:10

Christian Schlensker


People also ask

How to watch changes in $scope in AngularJS?

In angularjs $watch () function is used to watch the changes of variables in $scope object. Generally the $watch () function will create internally in angularjs to handle variable changes in application.

What is the use of $watch in AngularJS?

In angularjs $watch() function is used to watch the changes of variables in $scope object. Generally the $watch() function will create internally in angularjs to handle variable changes in application. Suppose in our angularjs applications if we want to create custom watch for some actions then it’s better to use $scope.watch function.

What is $watchcollection method in AngularJS?

The AngularJS $watchCollectionmethod is used to observe properties on a single object and notify you if one of them changes. In other word watchCollection is shallow watches the properties of an object and fires whenever any of the properties change.

How to watch changes in scope variables of a Watcher?

Once a watcher is configured with the scope, the listener function is called to initialize the watcher. This method is for watching changes of scope variables. This method has callback function which gets called when the watching properties are changed.


1 Answers

Use ng-change to submit the changes to the server and revert back to the previous value if the put fails.

Html

<select ng-model='color' ng-change="changeColor()"></select>

Controller

 $scope.$watch('color', function(newValue, oldValue) { 
      $scope.previousColor = oldValue;
 });

 $scope.changeColor = function(){
    $http.put('...', {color:  $scope.color}).error(function(){
      $scope.color =  $scope.previousColor;
    });   
 };

Plunker

like image 162
Jonathan Palumbo Avatar answered Oct 11 '22 16:10

Jonathan Palumbo