0

Is there any way to achieve what I'm trying to do in this fiddle?

I want to add a directive to an element using an Angular expression.

Example:

<div {{hello}}></div>

2 Answers 2

1

You need to insert the div inside the controller and not in the html markup in order to create directive dynamically. Over here I have used the $compile service inorder to dynamically generate the directive according the scope variable hello.

Controller Code:

function MainCtrl($scope, $compile) {
    $scope.flag = "disabled";
    $scope.hello = "hello";
    var el = $compile("<div " + $scope.hello + "></div>")($scope);
    var element = angular.element(document.querySelector('#mainID'));
    element.append(el);
}

Working Fiddle

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

Comments

0

I can see the idea but I'm not sure that's the appropriate place to declare your element. I would stick to attributes separate by type, or like @V31 where you create elements based on directives although his example seems to just create an element after the directive has compiled, I think you would need to recompile your directive again after that. Moreover I think the real power of your directive comes with it's ability to handle these events and maintain scope etc.

I would stick to attributes to declare your different element types, something like this -

Fiddle

    restrict: "EA",
    scope: {
        ngModel: "=",
        type: "@"
    },
    link: function (scope, el, attrs) { ...

Also ng-disabled already has an attribute for this.

ng-disabled="{{flag}}"

Comments

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.