如何将自定义角度指令附加到另一个自定义角度指令?

时间:2014-08-18 18:46:28

标签: angularjs angularjs-directive

我有两个自定义角度指令,一个重复追加第二个。问题是虽然附加了标签,但指令的模板却没有。当我手动插入时,它可以工作。

请参阅此jsfiddle:http://jsfiddle.net/HB7LU/5555/

以下是发生追加的代码:

myApp.directive('formList', function () {
    return {
        template: '<my-form></my-form>',
        require:'^repeatableForm',
        restrict: 'E',
        link: function (scope, element, attrs, repeatableFormCtrl) {
            scope.add = function () {
                console.log("test");
                element.append('appended <my-form></my-form>'); // apended<my-form></my-form> will appear but not the contents of <my-form>
            };
        }
    };
});

1 个答案:

答案 0 :(得分:3)

您必须使用$compile服务手动编译my-form指令,如下所示:

myApp.directive('formList', function ($compile) {
    return {
        template: '<my-form></my-form>',
        require:'^repeatableForm',
        restrict: 'E',
        link: function (scope, element, attrs, repeatableFormCtrl) {
            scope.add = function () {
                console.log("test");
                var newForm = $compile('<span>appended </span><my-form></my-form>')(scope);
                element.append(newForm);
            };
        }
    };
});

示例JSFiddle: http://jsfiddle.net/9L3whcqc/