Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a listener on a model in angularjs

Tags:

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?

like image 552
Rahul Avatar asked Mar 02 '13 13:03

Rahul


People also ask

What are event listeners in Angular?

This means, for event binding, it is Angular that controls when a listener starts or stops listening to their target events. Later in the series, we will look at using Renderer2 and RxJS to dynamically add and remove event listeners only if and when specific conditions are met.

Which function should we use to add event listener in a directive?

The ngOn directive adds an event listener to a DOM element via angular. element(). on(), and evaluates an expression when the event is fired.

What is $element in AngularJS?

$element is a jqlite (or jQuery if it is available) wrapped object containing a reference to some DOM objects as well as some helpful functions to interact with them. Any time you need to make changes to the DOM you would use $element .

What is event binding in AngularJS?

In Angular 8, event binding is used to handle the events raised by the user actions like button click, mouse movement, keystrokes, etc. When the DOM event happens at an element(e.g. click, keydown, keyup), it calls the specified method in the particular component.


1 Answers

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.

like image 97
pkozlowski.opensource Avatar answered Nov 03 '22 14:11

pkozlowski.opensource