0

I am trying to load -outside angular - dynamically a custom directive but the custom directive is not loaded in spite I have used $compile as the following : the custom directive is :

app.directive('mydirective',function (){
  return {
     template: '<div>Succeeded !</div>',
  }
})

and here the place I am loading dynamically the directive :

function showresultcust() {
angular.injector(['ng']).invoke(['$compile',
    function ($compile) {
        var scope = angular.element(document.getElementById("test1")).scope();
        var _html = '<div>{{name}}-</div><div mydirective >Not Succeed</div>';
        //var _html='<div >{{loaded}}</div>';
        var obj = $('#content');
        $('#content').html($compile(_html)(scope));
        // compile!!!
        $compile(obj.contents())(scope);
        scope.$digest();
        setTimeout(function () {
            scope.$apply();
        });
    }
]);
}

Please note that {{name}} in the dynamic HTML is loaded correctly, but not the custom directive. The full demo is in this 'plnkr.co' link

If you could do the correction directly in the 'plnkr' link above, I would appreciate that.

isherwood
  • 58,414
  • 16
  • 114
  • 157
JPNN
  • 383
  • 1
  • 7
  • 23

1 Answers1

0

The code is not compiling the mydirective directive because it is not part of the ng module. Add the module that contains the directive to the dependency list of the new injector.

//NOT this   
//angular.injector(['ng']).invoke(['$compile',

//Do this
angular.injector(['ng','tumblr']).invoke(['$compile',
    function ($compile) {
        var scope = angular.element(document.getElementById("test1")).scope();
        var _html='<div>{{name}}-</div><div mydirective >Not Succeed</div>';
        $('#content').html($compile(_html)(scope));
        scope.$apply();
    }
]);
}

The angular.injector function always creates a new injector and it needs all of the dependencies in the dependency list.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • It works ! Thanks @georgeawg i have just changed the tumblr to the actual name plunker – JPNN Apr 07 '16 at 01:40
  • One more question please , when I use templateUrl it is again not translating the template it is showing {{name}} , and it is only when load dynamically with the same way but using templateUrl here the example : http://plnkr.co/edit/L82o3zVbM5p76Kyfp8WE?p=preview – JPNN Apr 07 '16 at 18:15
  • Notice in my example the simplified the compile and apply. Your plnkr has two `$compile`s and a raw `setTimeout`. All that stuff in unnecessary. – georgeawg Apr 07 '16 at 20:51
  • thanks @georgeawg , I will update it , and can you please help why if I use templateUrl demo here :plnkr.co/edit/L82o3zVbM5p76Kyfp8WE?p=preview is not translated correctly ? – JPNN Apr 07 '16 at 21:25