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

Problem

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.

For example we have the following list representing the DIVs we wish to create

{"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

<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

<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

Problem courtesy of: allyLogan

Solution

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

Solution courtesy of: dfsq

Discussion

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. 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

Discussion courtesy of: RWAM

You can simply put your div to generate inside ng-repeat and set attributes and 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. for html tags refer this Q&A

Discussion courtesy of: asdf_enel_hak

When things go to complex in AngularJS, try to refactor. For that I would use some sort of directive.

There is already an answer in Stack Overflow, check it here: Dynamic Attributes with AngularJS

Discussion courtesy of: Thomas Kerbrat

This recipe can be found in it's original form on Stack Over Flow.