Given HTML in the form of
<p ng-repeat="item in items" my-directive="item">{{item.Description}}</p>
I would like to dynamically add ng-show
from within my-directive
. It seems it is not as easy as perhaps it could be. If my-directive
was an element instead of an attribute it could simply be done through a template, but alas the same support does not exist for attributes.
My first attempt used the $compile
service as described at Add directives from directive in AngularJS. However, that approach relies on the directive being a higher priority than any other, and is therefore applied before the ng-repeat
.
My current approach is to manually copy the source for ng-show
:
.directive('myDirective', ['$animate', function ($animate) {
function toBoolean(value) {
if (typeof value === 'function') {
value = true;
} else if (value && value.length !== 0) {
var v = angular.lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
value = false;
}
return value;
}
return {
scope: true,
link: function(scope, elem, attrs) {
scope.$watch("myWatchExpression",
function(isActive) {
$animate[toBoolean(isActive) ? 'removeClass' : 'addClass'](elem, 'ng-hide');
}
);
}
};
}])
However, that's obviously not a good long-term solution as it requires updating the custom directive whenever angular changes internally.
Is there any way to perhaps request a directive as an injectable and apply it to the element (without disrupting higher priority directives such as ng-repeat
)?
Edit to give context
The directive I'm trying to create is for tabbed items. Ideally the markup looks like:
<tab-container>
<button ng-repeat="tab in tabs" tab-button="{{tab.id}}">{{tab.name}}</button>
<div ng-repeat="tab in tabs" tab-view="{{tab.id}}"><ng-include src="{{tab.template}}"/></div>
</tab-container>
Thus I would like ng-click
and ng-class
directives on a tab-button
, and ng-show
on a tab-view
.