0

I have, probably, a pretty basic question. I have a div element with a number of anchors. I would like to add ng-click(for example) to every anchor. In jquery that would be a piece of cake, but with angular I'm not sure how to do this correctly. I believe the controller shouldn't know about layout, so it should be handled on a template level. Creating directive for something a simple as that also doesn't make much sense.

Any suggestions?

Anelook
  • 1,277
  • 3
  • 17
  • 28
  • why not just add `ng-click` to them ? – gkalpak Apr 15 '14 at 10:06
  • in ng-click I planned to call the same function, repeating it n-times doesn't look nice – Anelook Apr 15 '14 at 10:16
  • 1
    I don't think adding `ng-click` several times counts as code duplication. They all call the same function in the controller. When you create a form with several input tags, is that code duplication? – kubuntu Apr 15 '14 at 10:23
  • I had this questions too when I started with angular but I've learned that creating a directive for something simple as this wouldn't be much more work or produce more code overhead than doing it with jquery. Just look at part 5 of this awesome thread: http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background?rq=1. Should be just what you wanted. – mainguy Apr 15 '14 at 10:45

1 Answers1

0

Controller shouldn't know about layout, I agree.

I think it depends on the type of your app. If we're talking about 'forms' I believe you should go in using some sort of 'auto-generating' layout; I usually have some templates, partials and directives that create the form starting from an object like:

var form = [
    { name : "username", type : "text", required : true },
    { name : "password", type : "password", required : true },
    { name : "login", type : "button", onClick : $scope.loginHandler }
];

So it's not a problem: it's the directive/partial/whatever that manages button-types that do the right thing binding the onClick function to the right event.

But if your app is actually using a complex layout and you can't rely on something "autogenerated", the right way to bind it is specifying the handle function inside ng-click of every element/group of elements. That doesn't mean that the controller 'knows' about the layout: it's the layout that knows about the controller. Or you can mix jQuery with Angularjs; I don't like this approach and I think there are better ways, but it's always an option.

PS: sorry for my english.

Polmonite
  • 933
  • 6
  • 13