javascript - 使用 ng-repeat 创建 DOM 属性

标签 javascript angularjs angularjs-directive angularjs-ng-repeat

我有一个 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/

相关文章:

java - Spring文件上传 - 得到预期的MultipartHttpServletRequest : is a MultipartResolver configured?错误

javascript - 为什么 $compile 不能使用指令来处理服务?

AngularJS 指令数字格式屏蔽

javascript - 单击输入字段一段时间后,模型更改时 AngularJS View 未更新

javascript - CLEditor,在主窗口中将内容粘贴为文本功能

javascript - 深层链接到 Facebook 应用程序(使用 fb : protocol) not working from Facebook in-app browser

javascript按位运算符问题

javascript - 单击表 td 输入时每次都附加相同的 tr

javascript - 包含从属性创建 TemplateUrl 的页面的指令

javascript - 使用 AngularJS : auth cookie sent for/_session only 登录 CouchDB