Reputation: 6167
Using javascript and AngularJS how would I go about adding the Hours values into a variable. I've tried simple JS that I do know (limited knowledge, still beginner) and no luck.
<table class="table table-condensed table-striped table-hover">
<thead>
<tr>
<!--<td></td>-->
<td><a href="" ng-click="predicate= 'UserName'; reverse=!reverse">Employee <i class="fa fa-sort"></i></a></td>
<td><a href="" ng-click="predicate= 'TotalHours'; reverse=!reverse">Hours <i class="fa fa-sort"></i></a></td>
<td><a href="" ng-click="predicate= 'Date'; reverse=!reverse">Date <i class="fa fa-sort"></i></a></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="jobhour in jobHours | orderBy:predicate:reverse">
<!--<td>{{$index + 1}}</td>-->
<td>{{jobhour.UserName}}</td>
<td>{{jobhour.AdminHours*1 + jobhour.FieldHours*1 + jobhour.OtherHours*1 + jobhour.TravelHours*1 | number:2}}</td>
<td>{{jobhour.Date | date:medium}}</td>
</tr>
</tbody>
</table>
Above is the code for the ng-repeat on the table and you see I'm adding several values into that column already (this may be why I'm not sure on a simple way to approach this). The TOTAL value I'm trying to get is nothing more than a simple UI notification. I want to place this 'TOTAL SUM' into the label above next to Total Hours:
ANSWER FOR THIS SPECIFIC CODE:
Here's what I ended up doing and worked perfectly. Thanks for the help.
function addArr(arr){
var val = 0;
for (var i = 0; i < arr.length; i++) {
val += parseFloat(arr[i].AdminHours || 0) + parseFloat(arr[i].FieldHours || 0) + parseFloat(arr[i].TravelHours || 0) + parseFloat(arr[i].OtherHours || 0);
//val += arr[i].AdminHours + arr[i].FieldHours + arr[i].TravelHours + arr[i].OtherHours;
}
$scope.totalHours = val;
}
Upvotes: 0
Views: 183
Reputation: 35276
Have a function on your controller that loops through the array and adds the values together, then return and value. Something like this
var addArr = function(arr){
var val = 0;
for(var i = 0; i < arr.length; i++){
val += arr[i];
}
return val;
}
$scope.val = addArr(theArray);
Here's what I ended up doing and worked perfectly. Thanks for the help.
function addArr(arr){
var val = 0;
for (var i = 0; i < arr.length; i++) {
val += parseFloat(arr[i].AdminHours || 0) + parseFloat(arr[i].FieldHours || 0) + parseFloat(arr[i].TravelHours || 0) + parseFloat(arr[i].OtherHours || 0);
//val += arr[i].AdminHours + arr[i].FieldHours + arr[i].TravelHours + arr[i].OtherHours;
}
$scope.totalHours = val;
}
Upvotes: 1