angularjs、$compiled 模板和 ng-repeat [英] angularjs, $compiled templates and ng-repeat
问题描述
本质上,我在指令的编译函数中使用了两个模板.我在指令的编译阶段一劳永逸地编译它们(通过 $compile).在指令的链接阶段,我观察一个范围变量并将一个或另一个编译模板应用于该范围.
testApp.directive('testField', ['$compile', function ($compile) {返回 {限制:'E',范围:真实,编译:函数(tElement,tAttrs){var viewFn = $compile("<div>视图:<span ng-repeat='x in [1,2,3]'>{{x}}</span></div>");var editFn = $compile("<div>Edit: <span ng-repeat='x in [4,5,6]'>{{x}}</span></div>");返回函数(范围、元素、属性){varinnerScope = null;scope.$watch("mode", function (mode) {if (innerScope)innerScope.$destroy();innerScope = scope.$new();如果(模式=='视图'){element.empty().append(viewFn(innerScope));} 别的 {element.empty().append(editFn(innerScope));}});};}};}]);
它工作正常,除非模板包含一个不是根元素的 Ng-repeat,在这种情况下它的行为很奇怪:
要重现,请转到 http://plnkr.co/edit/RCqlNWTVdXVoMQCkFcQn?p=preview然后从编辑"切换到查看".
您会注意到 ng-repeat 的迭代次数随着时间的推移而增长.第一次,它显示 123 和 456,就像它应该的
第一次来回查看和编辑后,显示123123和456456
每次您在查看和编辑之间来回切换时,它都会不断添加一次迭代.
也许你可以像这个.
首先,您直接在视图中注入新的 dom.之后,抓住它并应用 $compile.
像这样;
var viewFn = "视图:{{x}};";...element.html(viewFn);...$compile(tElement.contents())(innerScope);
Essentially, I take two templates inside a compile function of a directive. I compile them once and for all (via $compile) in the compile phase of the directive. In the link phase of the directive, I watch a scope variable and applies one or the other compiled template to the scope.
testApp.directive('testField', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: true,
compile: function(tElement, tAttrs) {
var viewFn = $compile("<div>View: <span ng-repeat='x in [1,2,3]'>{{x}}</span></div>");
var editFn = $compile("<div>Edit: <span ng-repeat='x in [4,5,6]'>{{x}}</span></div>");
return function (scope, element, attrs) {
var innerScope = null;
scope.$watch("mode", function (mode) {
if (innerScope) innerScope.$destroy();
innerScope = scope.$new();
if (mode == 'VIEW') {
element.empty().append(viewFn(innerScope));
} else {
element.empty().append(editFn(innerScope));
}
});
};
}
};
}]);
It works fine, except when the template includes a Ng-repeat that is not the root element in which case it behave strangely:
To reproduce, go to http://plnkr.co/edit/RCqlNWTVdXVoMQCkFcQn?p=preview And switch a couple of time from Edit to View.
You'll notice the number of iterations of ng-repeat grows over time. First time, it displays 123 and 456, like it should
After the first back and forth between view and edit, it displays 123123 and 456456
And it keeps adding one iteration every time you do a back and forth between view and edit.
Maybe you can do like this.
Firstly, you inject new dom directly in your view. After, catch it and apply $compile.
like this;
var viewFn = "<div>View: <span ng-repeat='x in [1,2,3]'>{{x}}</span></div>";
...
element.html(viewFn);
...
$compile(tElement.contents())(innerScope);
这篇关于angularjs、$compiled 模板和 ng-repeat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!