3

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.

1
  • 1
    would ng-ifsolve your problem? like ng-if="item" then show your directive Commented May 11, 2016 at 12:49

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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>

3 Comments

yep, could also use ng-show depending on if you want to render to dom or not
@aw04 there is difference between ng-show and ng-if , ng-if removes the elements from the dom and moreover angular doesn't watches the same , in case of ng-show/ng-hide it doesn't remove elements from dom and it keeps on watching .
yes and sometimes that's ok, it's recommended for items that may change alot. i was just pointing it out as an option

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.