Using AngularJS 1.5, I've built a custom attribute directive, that adds a date-range-picker directive, and it's options, to the element :
app.directive('clSingleDatePicker', function($compile) {
var opts_single_date = {
singleDatePicker: true
};
return {
restrict: 'A',
compile: function compile(element, attrs) {
element.attr('date-range-picker', '');
element.attr('options', 'opts');
element.removeAttr("cl-single-date-picker"); //remove the attribute to avoid indefinite loop
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
},
post: function postLink(scope, iElement, iAttrs, controller) {
scope.opts = opts_single_date;
$compile(iElement)(scope);
}
};
}
};
});
When I'm adding this directive to a simple input like this:
<input cl-single-date-picker type="text" ng-model="someModel"/>
I'll get the required result in the DOM:
<input type="text" ng-model="someModel" class="ng-pristine ng-valid ng-scope ng-isolate-scope ng-empty ng-touched" date-range-picker="" options="opts" style="">
And the date-range-picker is active and doing it's work. However, If I'm adding a conditional directive to my element, In my case ng-switch-when:
<input ng-switch-when="1" cl-single-date-picker type="text" ng-model="someModel"/>
This element will not be rendered at all, even though, the directive function is being executed. How can I add my directive to an element with a conditional directive on it and have it rendered?
A working solution (Edited) By adding a priority value higher than the ng-switch (which is 1200 apparently), The customed directive is now being executed before the ng-switch-then directive, and the datepicker is being rendered.
EDIT: misunderstood the question
It looks like the
ng-switch-whenis also being applied to the attribute directive, but it either thinks it's not within anng-switchor it does not have access to the outer scope, so theng-switch-whenresolves tofalse.There are a couple of solutions:
1) Wrap the
inputin aspanand put theng-switch-whenon that instead of theinput2) Remove the
ng-switch-whenattribute in the directiveelement.removeAttr("ng-switch-when");Both seem to work (when experimenting in a Plunker). Personally, I prefer the first as it's all within the template.
Original answer:
ng-switchaffects the element it is on, not the attributes within it. There are a few ways of conditionally showing the custom attribute:If you wanted to use
ng-switch, you could have two inputs:Alternatively, you could add an extra attribute on your directive and do the check in the directive, e.g.
You may also be able to use this to conditionally apply the attribute (see this question). I haven't tried this myself.