1

i need to use directive from controller in angular 1.6.*.

I explain better with code.

Controller

$scope.directive = [
   "<span my-directive></span>",
   "<span my-directive2></span>",
   "<span my-directive3></span>"
]

HTML

<div>{{directive}}</div>

My solution is:

Controller

directive.forEach(function (item) {
    $compile(item)($scope).appendTo('.navbar');
})

HTML

<div class="navbar"></div>

But my solution is DOM dependent, is a bad solution.
I need a smart solution.

Any ideas?

Thanks!

2
  • mmmm, there is a lot of solutions, and as i see this is not work. But the most important of all, is FOR WHAT IS THIS CODE? Commented Oct 24, 2017 at 13:14
  • Most solutions use $compile but with respect to the parent that directives are bound to Commented Oct 24, 2017 at 13:19

2 Answers 2

1

You could create your own directive which will do this binding for you similarly to ng-bind and ng-bind-html.

Please consider the following example:

Directive

function MyBindCompileDirective($compile) {
    return {
        restrict: 'A',
        link(scope, elem, attrs) {
            attrs.$observe('myBindCompile', () => elem.html($compile(scope.myBindCompile)(scope).html()))
        }
    };
}

angular
    .module('app')
    .directive('myBindCompile', MyBindCompileDirective);

Usage in HTML

<div ng-repeat="item in directives" my-bind-compile="item"></div>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, is another way, but is DOM dependent too. and the scope is isolated, i can't.pass the data Example "<span my-directive3 myData='data'></span>"
Instead of an isolated scope you could just use attr.$observe, but the example with isolated scope seemed more relatable to me. I updated the answer to use $observe instead of $watch.
Your code give me a problem, but i have understand your idea. And i understand that is impossible without $compile and html(). Thank you!
Not sure what the problem is, but I am glad I could help.
0

I would iterate in a ngRepeat and put the directive directly, changing only what is needed. collection is defined in the controller

<div ng-repeat="model in collection">
 <span my-directive variable="model"></span>
</div>

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.