How can delegate a click event on my board, what I do is I tell element to find element with the class open-preview And I can not do it like I do. Because the li is created dynamically in ruby loop. I do not know how I can delegate a click event in angular instead of find.
HTML CODE
<ul>
<li open-preview>
<a ng-href="{{product.url}}" title="{{product.brand}}">
<img ng-src="{{product.urlImage}}" alt="{{product.brand}}">
</a>
<div class="descrip-product">
<p>{{product.descriptionExcerpt}}</p>
</div>
<span class="open-preview">Quick view</span>
</li>
</ul>
DIRECTIVE CODE
var app = angular.module('productPreview'),
app.directive('openPreview', function($compile, $templateCache, $timeout) {
return {
restrict: 'A',
transclude: false,
templateNamespace: 'html',
scope: true,
link: function(scope, element, attrs) {
element.find('.open-preview').bind('click', function() {
// function here
});
}
}
}):
It's better (if not outright required) to use an isolate scope because you are reusing the directive.
In isolate scope you can define how a directive can invoke an external (to the directive) function - this is done with scope: { param: "&" }
app.directive('openPreview', function() {
return {
restrict: 'A',
scope: {
openPreview: "&"
},
link: function(scope, element, attrs) {
element.find('.open-preview').bind('click', function() {
// invoke the function
scope.openPreview({p1: 'foo', p2: 'bar'});
});
}
}
}):
Then the usage is:
<li open-preview="onPreview(p1, 'xyz', p2)">
...
</li>