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!

MBielski
  • 6,628
  • 3
  • 32
  • 43
Daorithos
  • 45
  • 4
  • 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? – Álvaro Touzón Oct 24 '17 at 13:14
  • [Most solutions](https://stackoverflow.com/questions/15279244/dynamically-add-directive-in-angularjs) use `$compile` but with respect to the parent that directives are bound to – Aleksey Solovey Oct 24 '17 at 13:19

2 Answers2

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>
Vladimir Zdenek
  • 2,270
  • 1
  • 18
  • 23
  • Thanks, is another way, but is DOM dependent too. and the scope is isolated, i can't.pass the data Example `""` – Daorithos Oct 24 '17 at 15:13
  • 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`. – Vladimir Zdenek Oct 24 '17 at 15:29
  • Your code give me a problem, but i have understand your idea. And i understand that is impossible without $compile and html(). Thank you! – Daorithos Oct 24 '17 at 15:55
  • Not sure what the problem is, but I am glad I could help. – Vladimir Zdenek Oct 24 '17 at 16:03
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>
renatotkr
  • 68
  • 4