krish
krish

Reputation: 33

AngularJs apply custom directive to HTML conditionally

Is there a right way to apply custom directive to HTML template based on some condition

Eg: <li my-custom-directive="{{item}}">

I need to apply "my-custom-directive" only if {{item}} is defined.

Upvotes: 3

Views: 1553

Answers (3)

Shushanth Pallegar
Shushanth Pallegar

Reputation: 2862

It depends on your requirement , if you use it has as element instead of attribute you can achieve using ng-if.

for ex in the below code li wouldnt appear in the dom as and when item is undefined,

<my-custom-directive="{{item}}" ng-if="item">
    <li>{{item}}</li>
</my-custom-directive>

Upvotes: 1

Andrew Donovan
Andrew Donovan

Reputation: 552

Use ng-if, DOM is not inserted until condition is met.

AngularJS leaves a comment within the DOM for its reference,

so <li my-custom-directive="{{item}}"> would not be within the DOM at all until {{item}} is defined.

If you need to add directives dynamically to the DOM from a variable, use $compile provider. I've created myself a directive for such things

    angular.module('test', []).directive('directiveName', ['$compile',      function($scope) {
        return {
            link: function($scope, element, attrs, ctrl) {
            element.replaceWith($compile(attrs.direciveName)($scope))
        }
    }
    }]);

And you can use it as such:

<div directive-name="{{customDirectiveName}}"></div>

{{customDirectiveName}} being a $scope variable from somewhere else. From this point you could ng-repeat on JSON objects recieved from server, ect.

Upvotes: 1

aw04
aw04

Reputation: 11177

This feels like a design problem rather than a technical one.

Rather than apply the custom directive conditionally, simply figure out what to do inside the directive. Semantically, this makes more sense.

For instance, if item is undefined in this case, simply don't do something inside the directive.

Upvotes: 3

Related Questions