AngularJs ng-click VS jquery on ('click')

I'm new to angular and don't understand why I should use angular ng-click

for jQuery event listeners? Since the best practice is to only use one of these in my application (as per this high resolution vote ) Isn't there an elegant solution in angular to listen for events like in jquery?


<span>Box 1</span>
<span>Box 2</span>
<span>Box 3</span>

$("span").on('click',function() {
  // do something 



<span ng-click="doSomething();">Box 1</span>
<span ng-click="doSomething();">Box 2</span>
<span ng-click="doSomething();">Box 3</span>

$scope.doSomething = function(){
    // do something


What happens if I need to change the name of a function or completely remove it in angular, I have to go through all the code and remove the ng clicks.


source to share

4 answers

One reason not to use jQuery is that in this case the click handler will not trigger the digest in angular (no dirty check will be done, the clock will not fire, nothing will be updated).

IMHO random ng-click is ok, but if you need the same structure multiple times, you should write a directive so that you can say something like:

<box box-data="{{myModel.subModel}}"></box>


This way, you also don't need to worry about keeping the html and js in sync when refactoring - everything is completely encapsulated in the directive.



You can use ng-repeat


$scope.spans = ["Box 1", "Box 2", "Box 3"]



<span ng-repeat="s in spans" ng-click="doSomething()">{{s}}</span>




Yes, you will need to rewrite your code or leave "hg-click =" doSomething (); "and just change the doSomething function to // do nothing.



The only place where you should use jQuery code in your AngularJS app is in the custom directive (this is best practice).

So, if you really want to clean up the Spans tags, you need to create a custom directive that will specify all of your spans with a link function containing your aforementioned jQuery code, BUT this may not be very practical and is not recommended.

The best way is to stick with AngularJS directives like ng-click for something simple to react to the click event to have less unpredictable behavior.



All Articles