javascript - angular js revert change of scope property inside a watch statement - Stack Overflow

I have a select box that triggers an http PUT when it's changed.html:<select ng-model='col

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?

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?

Share edited Apr 7, 2015 at 5:32 Christian Schlensker asked Oct 23, 2013 at 19:39 Christian SchlenskerChristian Schlensker 22.5k20 gold badges78 silver badges122 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742402086a4437114.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信