使用Angular和ng repeat将Attributes添加到HTML DIV中

Using Angular and ng-repeat to add Attributes to an HTML DIV

本文关键字:添加 HTML DIV Attributes Angular ng repeat 使用      更新时间:2023-09-26

我们使用AngularJS,我们希望使用ng repeat创建一系列HTMLdiv,每个div具有不同的HTML属性。

例如,我们有下面的列表,表示我们希望创建的DIV

{"id":"year","class":"zone editable","contenteditable":"true","html":""},    
{"id":"analytics-image","class":"zone","html":""}    
{"id":"title","class":"zone","html":"Credit Assessment"},

并希望创建以下HTML

<div id="year" class="zone editable" contenteditable="true"></div>
<div id="analytics-image" class="zone"></div>
<div id="title" class="zone">Credit Assessment</div>

我有以下Javascript

<div ng-repeat="item in items">{{item.html}} </div>

其中items是上面示例中的键值对。

任何帮助都非常感谢

最灵活、最干净的方法是创建非常简单的指令来创建必要的属性:

.directive('attrs', function() {
    return {
        link: function(scope, element, attrs) {
            var attrs = angular.copy(scope.$eval(attrs.attrs));
            element.attr(attrs).html(attrs.html);
        }
    };
});

并像这样使用:

<div ng-repeat="item in items" attrs="item">{{item.html}}</div>

演示:http://plnkr.co/edit/QHEV1A0yawTzGEjvPiMq?p=preview

您可以访问以下值:

<div ng-repeat="item in items" id="{{item.id}}" class="{{item.class}}">{{item.html}} </div>

但是如果你的html里面有html标签,你的html就不会被正确呈现。使用这个替代:

<div ng-repeat="item in items" id="{{item.id}}" class="{{item.class}}" ng-bind-html="item.html"> </div>

看看https://docs.angularjs.org/api/ng/directive/ngBindHtml

当AngularJS中的情况变得复杂时,请尝试重构。为此,我会使用某种指令。

Stack Overflow中已有答案,请在此处查看:AngularJS 的动态属性

您可以简单地将div放在ng repeat和set属性和html 中生成

<div ng-repeat="item in items">
    <div id="{{item.Id}}" class="{{item.class}}">{{item.html}}</div>
</div>

只要item.html是原始文本,这就可以工作。对于html标签,请参阅以下问答;