I'm trying to create a directive that would allow an element to be defined as clickable or not, and would be defined like this:
<page is-clickable="true">
transcluded elements...
</page>
I want the resulting HTML to be:
<page is-clickable="true" ng-click="onHandleClick()">
transcluded elements...
</page>
My directive implementation looks like this:
app.directive('page', function() {
return {
restrict: 'E',
template: '<div ng-transclude></div>',
transclude: true,
link: function(scope, element, attrs) {
var isClickable = angular.isDefined(attrs.isClickable) && scope.$eval(attrs.isClickable) === true ? true : false;
if (isClickable) {
attrs.$set('ngClick', 'onHandleClick()');
}
scope.onHandleClick = function() {
console.log('onHandleClick');
};
}
};
});
I can see that after adding the new attribute, Angular does not know about the ng-click
, so it is not firing. I tried adding a $compile
after the attribute is set, but it causes an infinite link/compile loop.
I know I can just check inside the onHandleClick()
function if the isClickable
value is true
, but I'm curious how one would go about doing this with dynamically adding an ng-click
event because I may need to do with this with multiple other ng-*
directives and I don't want to add unnecessary overhead. Any ideas?