I am working on angularjs, and I have created some directives with bunch of HTML elements within its templates. I have assigned a controller for those directives. Below is my code snippet:
directives.directive('ngLd',function()
{
return {
restrict : "AE",
templateUrl:'partials/ld.html',
scope:{},
link : function(scope,element,attr)
{
var lbutton = element.find("span[class='lb-lk-comm']");
var dlbutton = element.find("span[class='lb-dlk-comm']");
if(lbutton && dlbutton)
{
lbutton.bind('click',function(event)
{
scope.likeAction(lbutton.hasClass("lb-voted-comm"),dlbutton.hasClass("lb-voted-comm"));
scope.$apply();
});
dlbutton.bind('click',function(event)
{
scope.dislikeAction(lbutton.hasClass("lb-voted-comm"),dlbutton.hasClass("lb-voted-comm"));
scope.$apply();
});
}
},
controller : "MyController"
};
});
In the above code, I have used a link function of bind the click event on required elements.
Another approach I could have followed to use the ngClick
directive directly over the elements, but that is sort of exposing method to client end.
My question is, am I following a good approach by binding click event ? or should I use ngClick
?
I am using angular.bootstrap(document,"myApp");
to bootstrap the angular module to document, so I was wondering if I could have similar thing to dynamically bind those events (click, hover, change etc) to my HTML elements, without exposing them to HTML pages.
1 Answer 1
I think you did the right thing, if you used ngClick
you would loose tooling: syntax highlighting, debugging, linting.
Other than that your code looks good, some minor nitpickings:
a single comma separate
var
statement is considered better:var lbutton = element.find("span[class='lb-lk-comm']"), dlbutton = element.find("span[class='lb-dlk-comm']");
You keep repeating
"lb-voted-comm"
, you should use a constant for it.- I only understood after reading
likeACtion
/dislikeAction
thatlbutton/dbutton
stand forlikeButton
,dislikeButton
( I thought it was left button, double click button or something ), you should spell out those variables names.
-
\$\begingroup\$ its lbutton for like button and dlbutton for dislike, its nothing just a span as I have mentioned. \$\endgroup\$Aman– Aman2014年03月10日 15:26:44 +00:00Commented Mar 10, 2014 at 15:26
-
1\$\begingroup\$ @Aman I understand, if you actually called the variables
likeButton
anddislikeButton
, then the code would be of higher quality/readability \$\endgroup\$konijn– konijn2014年03月10日 15:29:19 +00:00Commented Mar 10, 2014 at 15:29
Explore related questions
See similar questions with these tags.