AngularJS - 将元素附加到指令内的每个 ng-repeat 迭代 [英] AngularJS - Append element to each ng-repeat iteration inside a directive
问题描述
我在 <tr>
元素中使用了 ng-repeat 和一个指令.
I'm using a ng-repeat inside a <tr>
element together with a directive.
HTML:
<tbody>
<tr ng-repeat="row in rows" create-table>
<td nowrap ng-repeat="value in row | reduceString>{{value}}</td>
</tr>
</tbody>
指令:
app.directive('createTable', function () {
return {
link: function (scope, element, attrs) {
var contentTr = scope.$eval('"<tr ng-show="false"><td>test</td></tr>"');
$(contentTr).insertBefore(element);
}
}
}
);
虽然我可以在每次迭代中附加一个新的 Although I can append a new 你的孩子没有得到 Angular 绑定的原因是因为你缺乏编译它.当链接函数运行时,元素已经被编译,因此,Angular 被增强了.您所要做的就是手动 The reason why you don't get Angular binding inside your child is because you lack compiling it. When the link function runs, the element has already been compiled, and thus, Angular augmented. All you got to do is to 另一个提示:永远不要将元素包含在 jQuery ($) 中.如果您的页面中有 jQuery,则所有 Angular 元素都已经是 jQuery 增强元素. Another tip: you never enclose your elements in jQuery ($). If you have jQuery in your page, all Angular elements are already a jQuery augmented element. 最后,解决您所需要的正确方法是使用指令 Finally, the correct way to solve what you need is to use the directive 最后,请阅读完整的指令指南,这是一个宝贵的资源. As a last effort, read the entire Directive guide, this is a valuable resource. 这篇关于AngularJS - 将元素附加到指令内的每个 ng-repeat 迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!<tr>
元素,但我无法在将其添加到 DOM 后执行 angular 代码(例如里面的 ng-show).我错过了一些明显的东西吗?
<tr>
element to each iteration, I'm not able to get angular code executed after it's been added to the DOM (for example the ng-show inside the <tr>
). Am I missing something obvious? 推荐答案
$compile
您的内容.首先,不要评估您的模板,否则您将丢失绑定提示.$compile
your content by hand. First of, don't eval your template, or you will lose your binding tips.app.directive('createTable', function ($compile) {
return {
link: function (scope, element, attrs) {
var contentTr = angular.element('<tr ng-show="false"><td>test</td></tr>');
contentTr.insertBefore(element);
$compile(contentTr)(scope);
}
}
});
compile
函数(阅读 '编译过程和指令匹配'和'编译函数') 在编译前修改元素.compile
function (read 'Compilation process, and directive matching' and 'Compile function') to modify elements before its compilation.
登录
关闭