如何在单击时将自定义指令附加到另一个自定义指令中

时间:2016-08-18 10:06:01

标签: angularjs angularjs-directive

我有一个由按钮组成的自定义指令 当我单击此按钮时,我想要将已经定义为自定义指令的整行添加到自身,称为

这是HTML

 <tbody>
                <tr>
                    <row-creator></row-creator>
                </tr>
            </tbody>

这是按钮的指令声明

app.directive('rowCreator', function() {
return {
    restrict: "AE",
    template: "<button>Add Row</button>",
    link: function(scope, element, attrs){
        element.bind('click', function(){
           element.append(<exception-row></exception-row>);
           console.log('appended');
        })

    }
}});

但是,如果我将<exception-row>替换为不需要角度解释的元素,例如<p>this is some text</p>,则效果很好。这让我觉得它与编译有关,但我已经尝试了几个小时我都没有设法做到这一点。

2 个答案:

答案 0 :(得分:0)

您必须使用$compile编译HTML。所以在追加之后你会做类似的事情:

$compile(element.contents())(scope);

答案 1 :(得分:0)

使用模板:

app.directive('rowCreator', function() {
return {
    restrict: "AE",
    scope: {},
    template: "<button ng-click="addRow()">Add Row</button><exception-row ng-repeat="row in rows track by $index"></exception-row>",
    link: function(scope, element, attrs) {
       scope.rows = [];
       scope.addRow = function() {
           $scope.rows.push($scope.rows.length); // or whatever else you want
       };
    }
}});
相关问题