我创建了以下 ParentDirective
中使用的角度指令 ChildDirectivevar 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', function ($http, $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', 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 = '<child-directive></child-directive><child-directive></child-directive>';
elem.append(x);
$compile(x);
});
}
}
}
});
问题在于 childDirectives 不再出现,尽管在debeggur中它正在进入 childDirective 的编译方法
答案 0 :(得分:34)
您必须将已编译的元素链接到范围。由于您不再修改模板元素,因此应将新元素附加到链接元素。你可以这样做:
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('<child-directive></child-directive><child-directive></child-directive>');
element.append(x);
$compile(x)(scope);
});
}
}
}
}
});