鉴于我的 Controller 中的这些数据:
$scope.data = [
{id: "1", ElementType: "paragraph", text: "some content"},
{id: "2", ElementType: "listItem", text: "some list item content"},
{id: "3", ElementType: "quote", text: "some quote"}
]
在我看来,给定这个 ng-repeat:
<div ng-repeat="item in data">{{item.text}}</div>
如何呈现此 HTML? :
<p>Some content</p>
<ul>
<li>some list item content</li>
</ul>
<blockquote>some quote</blockquote>
我已经探索了 ng-switch 但它保留了父 div。换句话说,我想用基于对象属性的新标记替换 ng-repeat 生成的 HTML。
最佳答案
您可以使用 $compile
Angular 函数在指令内执行此操作,如 this 所示plnkr。
更新 Here is a plnkr that works better
这里是关键部分:
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
var htmlStr = '';
var repeat = attrs.repeat;
for(var i = 0; i< repeat; i++){
htmlStr += html;
}
ele.html(htmlStr);
$compile(ele.contents())(scope);
});
}
您的 Controller 将如下所示:
function MyController($scope) {
$scope.html = '<p>{{id}}</p>\
<ul>\
<li>{{ElementType}}</li>\
</ul>\
<blockquote>{{text}}</blockquote>';
}
从您的示例中,您将完全删除 ng-repeat 并仅使用此指令。一项更改是您将传入整个 $scope.data 并动态提取您想要在 html 字符串中使用的位。但因为它是一个字符串,所以通过简单的字符串连接应该很容易做到。
最后一件事 - 您可能需要添加一些标签,以便可以用数组中的动态数据替换静态内容。有点像 ng-repeat! (但仍然不同)。
最后,您可以使用 interpolate
来填充 html 字符串:
$interpolate(template)({
id: id,
ElementType: ElementType,
text: text
});
您将从 Controller 获取这些项目的数据的位置
关于javascript - 使用 ng-repeat 渲染条件标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25270741/