我创建了以下的角度指令,ParentDirective在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<br />'); } } }) wizardModule.directive('parentDirective',$compile) { return { restrict: 'E',compile: function (element,attrs) { var x = '<child-directive></child-directive><child-directive></child-directive>'; element.append(x); } }
这是正常工作,有几个儿童指令出现。
我想更新ParentDirective,从服务器获取childDirectives的列表。因此,我更新了ParentDirective代码来执行ajax调用,然后绘制ChildDirectives
var elem; wizardModule.directive('parentDirective',attrs) { var controllerurl = attrs.controllerurl; elem = element; if (controllerurl) { $http.get(controllerurl + '/GetWizardItems'). success(function (data,status,headers,config) { var x = '<child-directive></child-directive><child-directive></child-directive>'; elem.append(x); $compile(x); }); } } } });
问题是,childDirectives不再出现,尽管在debeggur中它正在进入childDirective的编译方法
您必须将编译的元素链接到作用域。而且,由于您不再修改模板元素,因此您应该将新元素附加到链接元素。你可以这样做:
原文链接:https://www.f2er.com/angularjs/145032.htmlvar elem; wizardModule.directive('parentDirective',attrs) { var controllerurl = attrs.controllerurl; elem = element; if (controllerurl) { return function(scope,element){ $http.get(controllerurl + '/GetWizardItems'). success(function (data,config) { var x = angular.element('<child-directive></child-directive><child-directive></child-directive>'); element.append(x); $compile(x)(scope); }); } } } } });