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

share|improve this question
up vote 1 down vote accepted

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

share|improve this answer

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

share|improve this answer

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

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.