John P
John P

Reputation: 1580

Angular dynamically created directive not executing

Plnkr sample: [http://plnkr.co/edit/jlMQ66eBlzaNSd9ZqJ4m?p=preview][1]

This might not be the proper "Angular" way to accomplish this, but unfortunately I'm working with some 3rd party libraries that I have limited ability to change. I'm trying to dynamically create a angular directive and add it to the page. The process works, at least in the sense where the directive element gets added to the DOM, HOWEVER it is not actually executed - it is just a dumb DOM at this point.

The relevant code is below:

<div ng-app="myModule">
    <div dr-test="Static Test Works"></div>
    <div id="holder"></div>
    <a href="#" onclick="addDirective('Dynamic test works')">Add Directive</a>
</div>
var myModule = angular.module('myModule', []);
myModule.directive('drTest', function () {
    console.log("Directive factory was executed");
        return {
            restrict: 'A',
            replace: true,
            link: function postLink(scope, element, attrs) {
                console.log("Directive was linked");
                $(element).html(attrs.drTest);
            }
        }
});
function addDirective(text){
    console.log("Dynamically adding directive");
    angular.injector(['ng']).invoke(['$compile', '$rootScope',function(compile, rootScope){
        var scope = rootScope.$new();
        var result = compile("<div dr-test='"+text+"'></div>")(scope);
        scope.$digest();
        angular.element(document.getElementById("holder")).append(result);       
}]);
}
&lt;/script&gt;

Upvotes: 0

Views: 116

Answers (1)

PSL
PSL

Reputation: 123739

While appending the directive to DOM you need to invoke with your module as well in the injector, because the directive drTest is available only under your module, so while creating the injector apart from adding ng add your module as well. And you don't really need to do a scope apply since the element is already compile with the scope. You can also remove the redundant $(element).

       angular.injector(['ng', 'myModule']).invoke(['$compile', '$rootScope',function(compile, rootScope){
          var scope = rootScope.$new();
          var result = compile("<div dr-test='"+text+"'></div>")(scope);
           angular.element(document.getElementById("holder")).append(result);
       }]);

Demo

Upvotes: 1

Related Questions