javascript - Adding a listener on a model in angularjs - Stack Overflow

changeHandler()

来源: javascript – Adding a listener on a model in angularjs – Stack Overflow

You’ve got 2 options to cover your use case:

Use the ng-change directive

You can write your input like so:

Search: <input ng-model="search.model" ng-change="changeHandler()">

where the changeHandler is a function defined on a scope.

Use a watch on a scope

by writing in your controller:

$scope.$watch('search.model', function(newVal, oldVal){
    console.log("Search was changed to:"+newVal);
    $scope.search.watch = newVal;
  });

Here is a working plunk illustrating both: http://plnkr.co/edit/Jgb2slcBFzLNKK0JFNyo?p=preview

The difference between the 2 approaches is that ng-change will fire only as a result of user’s iteractions with an input while $watch will fire for any model mutation – triggered from the input control or any other change to the model. So you can preciselly choose on which events you want to react.

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏