在另一个指令中使用angular指令

Ghy*_*hal 29 angularjs angularjs-directive

我创建了以下angular指令,在ParentDirective中使用的ChildDirective

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', function ($http, $compile) {
return {
    restrict: 'E',
    compile: function (element, attrs) {
        var x = '<child-directive></child-directive><child-directive></child-directive>';
        element.append(x);
    }
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,出现了几个儿童指令.

我想更新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);
            });
        }
    }
}
});
Run Code Online (Sandbox Code Playgroud)

问题是,childDirectives没有出现任何更多的,虽然在debeggur它正在进入到的编译方法childDirective

joa*_*mbl 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);
            });
          }
        }
    }
}
});
Run Code Online (Sandbox Code Playgroud)

  • 这个特殊的指令(`child-directive`)没有链接函数,没有控制器,也没有模板中的绑定所以它"工作",但你真的应该将它链接到一个范围 (2认同)
  • +1:救命答案!!! 如果我只能为这个答案给出100分!谢谢!它完美地工作:) (2认同)