Daorithos
Daorithos

Reputation: 45

AngularJS use Directive from controller

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!

Upvotes: 1

Views: 66

Answers (2)

Vladimir Zdenek
Vladimir Zdenek

Reputation: 2290

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>

Upvotes: 1

renatotkr
renatotkr

Reputation: 68

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>

Upvotes: 0

Related Questions