我可以动态加载 AngularJS 指令吗 templateUrl
什么时候在 table 上工作?
我有以下 HTML,重复 tr
用fw-rule
指令:
<tbody>
<tr ng-repeat="rule in data | orderBy:predicate:reverse" fw-rule="rule">
</tr>
</tbody>
我想要那个 tr
的内容不同,取决于“编辑”变量的状态。
下面是我的一个部分(另一个只是布局的变体):
<td><input type="checkbox"></td>
<td ng-click="isEditing=!isEditing">{{ fwRule.name }}<br><span class="rule-description">{{ fwRule.description }}</span></td>
<td>{{ fwRule.source }}</td>
<td>{{ fwRule.destination }}</td>
<td>{{ fwRule.protocol }}</td>
<td>{{ fwRule.schedule }}</td>
<td>{{ fwRule.action }}</td>
<td>{{ fwRule.reporting }}</td>
我在SO这里复习了以下两个问题,几乎给了我答案:
但是,他们都调用写指令的template
使用 <div ng-include"getTemplateUrl()"></div>
,例如:
app.directive('fwRule', function () {
return {
restrict: 'A',
scope: {
fwRule: '='
},
controller: function ($scope) {
$scope.getTemplateUrl = function () {
// a check would be made here to return the appropriate partial
return 'partials/RuleEditTableRow.html'
}
},
link: function (scope, element, attrs) {
},
template: '<div ng-include="getTemplateUrl()"></div>'
};
});
这在我的情况下不起作用,因为 div
不是 tr
的有效子项(也不是 span
,我也试过)。因此,浏览器会在表格外呈现该内容。
有没有办法动态更新 template
指令,不使用 ng-include
, 以便它可以在表内运行?
最佳答案
您可以使用$compile 服务来编译正确的模板
app.directive('fwRule', function ($compile) {
return {
restrict: 'A',
scope: {
fwRule: '='
},
controller: function ($scope) {},
link: function ($scope, element, attrs) {
var template = '<td>cell 1</td><td>cell 2</td>';
angular.element(element).html(template);
$compile(element.contents())($scope);
}
};
});
我想我可以在这个 fiddle 中使用您的代码:http://jsfiddle.net/ztv5gwwx/4/
关于javascript - 表行的 AngularJS 指令中的动态 `template`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22212970/