Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to handle events in AngularJS in this case?

I am absolutly new in AngularJS and I have the following doubt about how to handle event in Angular.

So I know if in a view I have something like this:

<input type="text" ng-model="handle" />

it means that exist a 2 way binding between this input element in the dom and an handle variable into the Angular $scope, for example:

$scope.handle = '';

So any change that happen into this input object implies a change of the handle property in the $scope and vice-versa.

So, into the Angular applcation, I can explicitly declare a whatcher

// I explicitly declare a whatcher on the handle property: when the value of this propertu change the function() is performed:
$scope.$watch('handle', function(newValue, oldValue) {

    console.info('Changed!');
    console.log('Old:' + oldValue);
    console.log('New:' + newValue);

});

So it should have the same meaning of manually adding a classic vanilla JavaScript EventListener (by the addEventListener() on the object that I want to observe in a classic old vanilla JavaScript application (that don't use Angular).

When something change on the input value the function associated to the whatcher is performed.

Ok it is pretty clear for me.

Now I say that I can also do something like this.

Into the HTML code I can have something like:

<input type="button" value="Click Me" ng-click="alertClick()" />

And in the Angular controller I will have something like:

$scope.alertClick = function() {
    alert("Clicked !!!");
}

So it seems like the ng-Click directive perform a function that is a $scope field when there is the click event on the button.

But can I do the same operation as done in the first example? Can I do it declaring a whatcher on the button if it is associated to a model object by the ng-model="handle" directive?

When is better use the first method and when is better the second method to handle events in AngularJS?

like image 458
AndreaNobili Avatar asked Dec 28 '25 18:12

AndreaNobili


1 Answers

ngModel is used to bind an imput form the UI to your controller

ngClick is just a regular javascript expression that have access to your controller scope that will be executed at the click event.

Here you have to use ng-click.

With angular a good practice is to avoid using function like addEventListener() or Jquery other function... Because AngularJS wrap all this functionality and will run digest loop or other voodoo magic if necessary.

like image 69
B0ltz Avatar answered Dec 30 '25 23:12

B0ltz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!