简体   繁体   English

使用Angular和ng-repeat将属性添加到HTML DIV

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

we are using AngularJS and we are looking to create a series of HTML DIVs using ng-repeat with different HTML Attributes for each DIV. 我们正在使用AngularJS,并且正在寻求使用ng-repeat为每个DIV创建具有不同HTML属性的一系列HTML DIV。

For example we have the following list representing the DIVs we wish to create 例如,我们有以下列表表示我们要创建的DIV

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

and would like to create the following HTML 并希望创建以下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>

I have the following Javascript 我有以下Javascript

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

Where items is the key value pair from the above example. 其中项目是上述示例中的键值对。

Any help is most appreciated 任何帮助是最感激的

The most flexible and clean approach would be to create very simple directive to create necessary attributes: 最灵活和简洁的方法是创建非常简单的指令以创建必要的属性:

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

and use it like this: 并像这样使用它:

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

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

You can access on the values like this: 您可以访问像这样的值:

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

But your html wouldn't be rendered correct if you have html tags inside. 但是,如果您具有html标记,则html不会正确显示。 Use this instead: 使用此代替:

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

Have a look at https://docs.angularjs.org/api/ng/directive/ngBindHtml 看看https://docs.angularjs.org/api/ng/directive/ngBindHtml

You can simply put your div to generate inside ng-repeat and set attributes and html 您可以简单地将div放在ng-repeat内部并设置属性和html

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

this would work as long as you item.html is raw text. 只要您item.html是原始文本,它就可以工作。 for html tags refer this Q&A 有关html标签的信息,请参阅此问答

When things go to complex in AngularJS, try to refactor. 当AngularJS中的事情变得复杂时,请尝试重构。 For that I would use some sort of directive. 为此,我将使用某种指令。

There is already an answer in Stack Overflow, check it here: Dynamic Attributes with AngularJS 堆栈溢出中已有一个答案,请在此处检查: AngularJS的动态属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM