2

I have two custom directives (restrict : 'A') which are working well (custom1 and custom2)

In my html page I would like to use either custom1 attribut or custom2 attribut on a div depending on a condition. For example I would like to write something like this :

<div condition?custom1:custom2 />

I don't want to use ng-if like in the following code:

<div id='main-div' ng-if="map.2d==true" custom1 />
<div id='main-div' ng-if="map.2d==false" custom2 />

Is there a way to write such a condition for attribut custom directives?

1 Answer 1

1

Update

You could build a separate directive which dynamically compiles the required directive:

app.directive('dynamicDirective', function($compile) {
  return {
    restrict: 'A',
    replace: true,
    scope: {
      dynamicDirective: '='
    },
    link: function(scope, elem, attrs) {
      var e = $compile("<div " + scope.dynamicDirective + "></div>")(scope);
      elem.append(e);
    }
  };
});

It can be used as follows (in this sample someDirective is defined on the scope and has the name of the required directive):

<div dynamic-directive="someDirective"></div>

Here is a sample

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

2 Comments

Are you sure about the syntax ? It seems that it's not working. But anyway I would like to use a 'A' directive since it's not a css style that I want to 'inject' but a real behaviour on my html element.
@clement you are right it doesn't work as the interpolation runs after the directive compilation. I will update my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.