Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
88
rated 0 times [  90] [ 2]  / answers: 1 / hits: 36137  / 11 Years ago, sat, march 2, 2013, 12:00:00

I currently have a model which is the value of a search box. The search operation is performing perfectly but I also want yet another feature to be performed when the search text is modified. So i wanna add a listener or watch the model variable. How can I do it?


More From » angularjs

 Answers
92

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.


[#79883] Friday, March 1, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alysas

Total Points: 616
Total Questions: 111
Total Answers: 124

Location: Slovenia
Member since Wed, Apr 6, 2022
2 Years ago
;