简体   繁体   中英

Angular directive inside ng-template with modal

I am curious about the way angular works with preloading directives since I have a problem with a directive that resides in a <script> tag and ng-template .

When I pause execution in chrome dev-tools, during the initial document load, I can clearly see that the code inside the directive's controller does not get called if my directive lies in some arbitrary template. Here is the example code, when eg myDirective is included in index.html as a part of myModule .js module, also included both in index and in the main app module:

This is some other directive's html containing the problematic myDirective

<script type="text/ng-template" id="callThis">
  <myDirective></myDirective>
</script>`

and I call it on click with ngDialog like this

ngDialog.open({
  template: 'callThis',
  scope: $scope
}); 

and it can't run the directive since it doesn't have any html to work with (thats the error, about some html element missing).

Finally here is the code for the module which holds myDirective

angular.module('myModule', ['myDirectiveTemplates', 'myDirectiveDirective'])
angular.module('myDirectiveTemplates', []).run(["$templateCache", function($templateCache) {$templateCache.put("myDirectiveTemplate.html","<h1></h1>");}]);
angular.module('myDirectiveDirective', []).directive('myDirective', function ($window, $templateCache) {
  return {
    restrict: 'E', 
    template: $templateCache.get('myDirectiveTemplate.html'),
    controller: function($scope) {
      //some arbitrary code
    }
  };
})

Interestingly if i put <my-directive></my-directive> right in index.html file it works ok, and the code inside the controller gets loaded on startup. I'm unsure how to solve this.

From what I understand of this problem you need to use the $compile service. There is a tutorial here that might help : $compile

The reason given in the tutorial is:

"The newly minted template has not been endued with AngularJS powers yet. This is where we use the $compile service..."

And quoted from the Angular Docs:

Compiles a piece of HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

Here is a brief code example as per the tutorial :

app.directive('contentItem', function ($compile) {
    /* EDITED FOR BREVITY */

    var linker = function(scope, element, attrs) {
        scope.rootDirectory = 'images/';

        element.html(getTemplate(scope.content.content_type)).show();

        $compile(element.contents())(scope);
    }

    /* EDITED FOR BREVITY */
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM