vru*_*erg 18 angularjs angularjs-ng-repeat
我在使用ng-repeat指令和我自己的自定义指令时遇到了问题.
HTML:
<div ng-app="myApp">
<x-template-field x-ng-repeat="field in ['title', 'body']" />
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
angular.module('myApp', [])
.directive('templateField', function () {
return {
restrict: 'E',
compile: function(element, attrs, transcludeFn) {
element.replaceWith('<input type="text" />');
}
};
});
Run Code Online (Sandbox Code Playgroud)
这里的问题是什么都没有被替换.我想要完成的是2x输入字段的输出,在DOM中完全替换'x-template-field'标签.我怀疑是因为ng-repeat正在同时修改DOM,所以这不起作用.
根据这个 Stack Overflow问题,接受的答案似乎表明这在早期版本的AngularJS(?)中实际上有效.
虽然element.html('...')实际上将生成的HTML注入到目标元素中,但我不希望HTML作为模板标记的子元素,而是在DOM中完全替换它.
基本上,出于与上述相同的原因,我不希望生成的HTML作为重复标记的子元素.虽然它可能在我的应用程序中得体,但我仍然觉得我已经调整了我的标记以适应Angular,而不是相反.
我没有找到任何方法来改变从'template'/'templateUrl'属性中检索到的HTML.我想要注入的HTML不是静态的,它是从外部数据动态生成的.
大概.:-)
任何帮助表示赞赏.
小智 16
您的指令需要先ng-repeat使用更高的优先级运行,因此在ng-repeat克隆元素时,它可以选择您的修改.
" 指令"用户指南中的" 编译/链接分离背后的原因 "部分介绍了ng-repeat的工作原理.
在当前的ng-repeat优先级是1000,所以任何高于这个应该这样做.
所以你的代码是:
angular.module('myApp', [])
.directive('templateField', function () {
return {
restrict: 'E',
priority: 1001, <-- PRIORITY
compile: function(element, attrs, transcludeFn) {
element.replaceWith('<input type="text" />');
}
};
});
Run Code Online (Sandbox Code Playgroud)
将您的内容放入ng-repeat模板中。您可以修改元素的属性并相应地修改指令以确定是否需要 ng-repeat,或者在指令编译中使用哪些数据
HTML(属性):
<div ng-app="myApp" template-field></div>
Run Code Online (Sandbox Code Playgroud)
JS:
angular.module('myApp', [])
.directive('templateField', function () {
return {
restrict: 'A',
template:'<input type="text" value="{{field}" ng-repeat="field in [\'title\',\'body\']" />'
};
});
Run Code Online (Sandbox Code Playgroud)
演示: http: //jsfiddle.net/GDfxd/3/
也可用作元素:
HTML(元素):
<div ng-app="myApp" >
<template-field/>
</div>
Run Code Online (Sandbox Code Playgroud)
JS
angular.module('myApp', [])
.directive('templateField', function () {
return {
restrict: 'E',
replace:true,
template:'<input type="text" value="{{field}}" ng-repeat="field in [\'title\',\'body\']" />'
};
});
Run Code Online (Sandbox Code Playgroud)
演示: http: //jsfiddle.net/GDfxd/3/