Reputation: 333
I'm new to angular and failing to understand why should i use angular ng-click
over jQuery event listeners? Since the best practice is to use only one of them in my App (according to this highly up voted answer) Isn't there any elegant solution in angular to listen to events such as in jquery?
jQuery
<span>Box 1</span>
<span>Box 2</span>
<span>Box 3</span>
$("span").on('click',function() {
// do something
});
Angular
<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 will happen if i'll need to change the function name, or remove it completely, in angular i'll have to go over the entire code and remove the ng-clicks.
Upvotes: 3
Views: 2923
Reputation: 5812
One reason not to use jQuery is that in that case the click handler will not trigger a digest in angular (no dirty checking will be done, no watches will fire, nothing will be updated).
IMHO the occasional ng-click is fine, but if you need the same structure repeatedly, you should write a directive, so that you can say something like:
<box box-data="{{myModel.subModel}}"></box>
That way you would also not need to worry so much about keeping html and js in sync when refactoring - everything is neatly encapsulated in the directive.
Upvotes: 0
Reputation: 3056
The only place where you should use jQuery code in an AngularJS application is in a custom directive (it's a best practice).
So, if you really want to clean up your spans tags, you have to create a custom directive englobing all your spans with a link function containing your aforementioned jQuery code, BUT it may not be very practical nor a good idea.
The best way is to stick to AngularJS directives like ng-click for something as simple as to react to a click event, to have less unpredictable behaviors.
Upvotes: 0
Reputation: 7744
You can use ng-repeat
In JS
$scope.spans = ["Box 1", "Box 2", "Box 3"]
In HTML
<span ng-repeat="s in spans" ng-click="doSomething()">{{s}}</span>
Upvotes: 2
Reputation: 5793
Yes, you will need to rewrite your code or leave the "hg-click="doSomething();" parts and just change the doSomething function as // do nothing.
Upvotes: 0