我有一个 json,我用它用 angularjs 动态创建元素。
json 有一个键值对数组,我希望将其呈现为元素上的属性。该数组可以包含自定义data-属性或事件,例如onclick。
假设 json 具有以下结构:
var arr = [
{ key : "data-id" , value : "10" },
{ key : "onclick" , value : "javascript:window.document.location.href='www.google.com'" }
]
任何人都可以为我提供一个解决方案,让我可以将上述数组中的对象渲染为元素的属性。
注意:上面的数组arr将是其他对象的属性。
最佳答案
您应该为此编写一个简单的指令,它将设置元素的属性。例如:
app.directive('attributes', function($parse) {
return {
scope: { attributes: '=attributes' },
link: function(scope, element) {
var attributes = scope.attributes,
el = element[0];
attributes.forEach(function(attr) {
el.setAttribute(attr.key, attr.value);
});
}
};
});
然后你可以像这样使用它:
<div attributes="elems">Some element</div>
它将被渲染:
<div attributes="elems" class="ng-isolate-scope" data-id="10" onclick="javascript:window.document.location.href='www.google.com'">Some element</div>
演示:http://plnkr.co/edit/0Yns3S4aYKWlgtpkHhMo?p=preview
关于javascript - 使用 ng-repeat 创建 DOM 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25402954/