在AngularJS的另一个指令模板中添加动态指令

Adding a dynamic directive inside another directive template in AngularJS

本文关键字:指令 添加 动态 另一个 AngularJS      更新时间:2023-09-26

我想在另一个指令模板中添加动态指令。如你所见,我想在指令模板中添加另一个指令如何在那里添加那些动态指令

请帮

return {
restrict: 'AE',
require :'^awkGrid',
templateUrl: 'views/shutter.html',
link : function(scope, element, attr, controllerInstance){
    //Set the header
    scope.items = [];
    angular.forEach(scope.rowData, function(value, key) {
        var obj = {
            key : key,
            value : value
        };

        template = <country name="'+value.country+'" id="'+key+'"></country>;
        scope.items.push(template);
    });
};
//Inside shutter.html file
 <div data-ng-repeat="item in items" class="ag-row action-row"
 ng-class-odd="'ag-row-even'"
 ng-class-even="'ag-row-odd'"
 ng-class="{'ag-row-selected':$index == selectedRow}"
 ng-click="setClickedRow($index,$event)">
<div class="ag-cell">
            {{item}} //Not working ,Prinitng the string
    <country name="india" id="-1"></country> //Working
</div>

要动态切换出指令的整个模板,你必须将元素的html设置为所需的新模板,然后将元素的内容传递给$compile以将其与$scope绑定。

element.html('<h1>Dynamic Content</h1>').show();

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

这些都应该在相关指令的link函数中定义。

你必须重新编译你的指令。在link函数的末尾添加以下代码:

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

答案在这里

当然,你必须把服务$compile作为依赖项添加到你的指令中。