Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs apply custom directive to HTML conditionally

Tags:

angularjs

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.

like image 451
krish Avatar asked Jul 23 '26 19:07

krish


2 Answers

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.

like image 147
aw04 Avatar answered Jul 27 '26 12:07

aw04


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.

like image 41
Andrew Donovan Avatar answered Jul 27 '26 11:07

Andrew Donovan