I have a directive <my-dir></my-dir>
and the directive should always have a specific functionality provided through angular attributes: <my-dir ng-show="ctrl.shown"></my-dir>
. Here ctrl is the controller defined through controllerAs: 'ctrl'
on the directive's definition.
I would like to simplify this directive and avoid mistakes by adding the attribute automatically when the directive is compiled. That way other users only have to type <my-dir>
. Adding an attribute to a directive is simple, but these new attributes don't seem to get compiled.
app.directive("myDir", function() {
console.log('myDir');
return {
restrict: 'E',
controller: 'DirectiveController',
controllerAs: 'ctrl',
template: '<span>Controller Content</span>'
// Attempt to attach the 'ng-show' attribute to the element
link: function($scope, $element, attrs) {
$element.attr('ng-show', 'ctrl.shown');
}
};
});
I've tried a bunch of different things: adding the attribute in link:
, in compile:
and even using $compile($element[0]['my-dir'])($scope)
after adding the attribute..
Example plnkr: http://plnkr.co/edit/PREavAIn1vqUdZYLsypt?p=preview
Example plnkr using the ctrl.shown
: http://plnkr.co/edit/dTWIzClZG4YpE76AMCWk?p=preview