Use an angular directive inside another directive

匿名 (未验证) 提交于 2019-12-03 01:08:02

问题:

I have created the below angular directives, ChildDirective that is used inside ParentDirective

var wizardModule = angular.module('Wizard', []);  wizardModule.directive('childDirective', function ($http, $templateCache, $compile, $parse) { return {     restrict: 'E',     scope: [],     compile: function (iElement, iAttrs, transclude) {         iElement.append('child directive
'); } } }) wizardModule.directive('parentDirective', function ($http, $compile) { return { restrict: 'E', compile: function (element, attrs) { var x = ''; element.append(x); } }

This was working normally and several child directives appeared.

I wanted to update the ParentDirective, to get the list of childDirectives from the server. Hence I updated the ParentDirective code to do an ajax call and then draw the ChildDirectives

var elem; wizardModule.directive('parentDirective', function ($http, $compile) { return {     restrict: 'E',     compile: function (element, attrs) {         var controllerurl = attrs.controllerurl;         elem = element;          if (controllerurl) {             $http.get(controllerurl + '/GetWizardItems').             success(function (data, status, headers, config) {                 var x = '';                 elem.append(x);                 $compile(x);             });         }     } } }); 

The problem is that the childDirectives does not appear any more, although in the debeggur it is entering to the compile method of the childDirective

回答1:

You have to link the compiled element to the scope. And since you're no longer modifying the template element you should append the new elements to the linked element. YOu can do it like this:

var elem; wizardModule.directive('parentDirective', function ($http, $compile) { return {     restrict: 'E',     compile: function (element, attrs) {         var controllerurl = attrs.controllerurl;         elem = element;          if (controllerurl) {           return function(scope,element){             $http.get(controllerurl + '/GetWizardItems').             success(function (data, status, headers, config) {                 var x = angular.element('');                 element.append(x);                 $compile(x)(scope);             });           }         }     } } }); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!