user1319182 user1319182 - 1 year ago 84
AngularJS Question

Looping through template items in Angular

I'm still new to Angular and am having a hard time updating items in an elegant way. I have the following code :

<div class="curative col-md-3" ng-repeat="c in curatives">
<span class="title">{{c.name}}</span>
<input class="equ" />
<input class="for" />
</div>


And in my app, I have this

$scope.curatives = [
{'name': 'Curative 1'},
{'name': 'Curative 2'}
];


No problem so far. Now I want to show a summary of the values in the different input fields, to have something like

Curative 1 : X | Y
Curative 1 : A | B


The only way I found was using plain JavaScript, which looks like this:

var items = document.getElementsByClassName('curative').length;
var target = document.getElementById('results');
var html = '';

for (var i = 0; i < items.length; i++) {
html+= "<div class='row'>"
+"<span class='col-md-6'>"+ items[i].getElementsByClassName('title')[0].html() +"</span>"
+"<span class='col-md-6 curative_value'>"+ items[i].getElementsByClassName('equ')[0].html() +" | "+ items[i].getElementsByClassName('for')[0].html() +"</span>"
+"</div>";
}


Is there a more elegant way to do this using Angular only?

Thanks

Answer Source

You could add properties for equ and for, and use ng-model to bind to them:

Controller:

$scope.curatives = [
    {'name': 'Curative 1', 'equ': '', 'for': '' },
    {'name': 'Curative 2', 'equ': '', 'for': '' }
];

Template:

<div class="curative col-md-3" ng-repeat="c in curatives">
    <span class="title">{{c.name}}</span>
    <input class="equ" ng-model="c.equ" />
    <input class="for" ng-model="c.for" />
</div>

<div ng-repeat="c in curatives">
    {{ c.name }} : {{ c.equ }} | {{ c.for }}
</div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download