简体   繁体   中英

Angular $scope.$watch for variables that changed only from the form (ng-model directive)

I have a listener that sends HTTP request to a server when I have changes in a model.

JS code:

$scope.a = 1;
$scope.$watch('a', function(newValue, oldValue) {
    sendSaveRequest(newValue);
});

HTML form:

<form>
    <input ng-model="a" />
</form>

This code works fine. But I also have a web socket connection with my web server. And if somebody else changes this model everybody should update this model, but they don't need to send the request to the server in this case:

socket.on('change', function(newValue) {
    $scope.a = newValue;
    $scope.$apply();
});

How to listen the model changes that occured only from the HTML form (ng-model directive)?

Use the ng-change directive:

<form>
    <input ng-model="a" ng-change="sendSaveRequest(a)"/>
</form>
$scope.sendSaveRequest = sendSaveRequest;

The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model.

It will not be evaluated:

  • if the model is changed programmatically and not by a change to the input value

For more information, see AngularJS ng-change Directive API Reference .

When model value is changing ,template is updating.When change in the template,it is written to the console immediately.

Sample link for ng-model directive: http://jsfiddle.net/BtrZH/168/

you just put the socket change out of the digest cycle like below. In this case watcher will not be called and hence no server call.

socket.on('change', function(newValue) {
  setTimeout(function() {
      $scope.a = newValue;
  }, 1000);
});

You can use Angular's ng-blur directive on your input instead of adding the watch in your controller.

In HTML:

<input ng-model="a" ng-blur="onBlur()"/>

The $scope.ngBlur function (defined below) will be called only after user changes the value manually on the form. Changing the value programatically (ie $scope.a = newValue;) will not call the function.

In controller:

$scope.a = '';
$scope.oldValue = $scope.a;

$scope.onBlur = function() {
  if ($scope.a !== $scope.oldValue) {
      $scope.oldValue = $scope.a;
      console.log('Request sending with value: ' + $scope.a);
      sendSaveRequest($scope.a);
  }
};

socket.on('change', function(newValue) {
    $scope.a = newValue;
    $scope.$apply();
});

Here you can find the plunker: http://plnkr.co/edit/iczEWILyp5y0QuZBML80 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM