2

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

allyLogan
  • 403
  • 2
  • 6
  • 13

4 Answers4

3

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

dfsq
  • 191,768
  • 25
  • 236
  • 258
2

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

gzc
  • 8,180
  • 8
  • 42
  • 62
RWAM
  • 6,760
  • 3
  • 32
  • 45
0

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

Community
  • 1
  • 1
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84
0

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

Community
  • 1
  • 1
Thomas Kerbrat
  • 106
  • 1
  • 7