I have the below code which uses the data in the staff array to calculate the staff members pay.
'use strict';
var app = angular.module('app', []);
app.factory('staffFactory', function ($http) {
var staff = [
{"id": "1","name": "Kate","rate": "10", "hours": "10"},
{"id": "2","name": "John","rate": "20", "hours": "10"},
{"id": "3","name": "Matt","rate": "15", "hours": "10"}
];
function calcPayInner(){
var unique = {},
distinct = [],pay = [];
for (var i in staff) {
if (typeof (unique[staff[i].id]) == "undefined") {
distinct.push(staff[i].id);
}
unique[staff[i].id] = unique[staff[i].id] || {pay:0};
unique[staff[i].id].name = staff[i].name;
unique[staff[i].id].pay += (parseInt(staff[i].rate, 10) * parseInt(staff[i].hours, 10));
}
for (var p in unique) {
pay.push([p, unique[p]]);
pay.sort(function (a, b) {
return (b[1].pay - a[1].pay);
});
}
return pay;
}
var staffService = {};
staffService.allStaff = function () {
return staff;
};
staffService.CalcPay = function () {
return calcPayInner();
};
return staffService;
});
app.controller('MainCtrl', ['$scope', 'staffFactory', function ($scope, staffFactory) {
$scope.staff = staffFactory.allStaff();
console.log($scope.staff);
$scope.CalcPay = staffFactory.CalcPay();
$scope.keyPress = function(keyCode){
$scope.CalcPay = staffFactory.CalcPay();
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl">
<table>
<tr><td>name</td><td>rate</td><td>hours</td></tr>
<tr ng-repeat="s in staff">
<td>{{s.name}}</td>
<td><input ng-keyup="keyPress(s.rate)" ng-model="s.rate"></td>
<td><input ng-keyup="keyPress(s.hours)" ng-model="s.hours"></td>
</tr>
</table>
<table>
<tr><td>name</td><td>pay</td></tr>
<tr ng-repeat="b in CalcPay">
<td>{{b.1.name}}</td>
<td>{{b.1.pay}}</td>
</tr>
</table>
</div>
</div>
This all works as intended however now I want to get the staff data from an API call rather than hard coded data.
I have tried the below. (see plnkr)
var staff = [];
var test = $http.get('staff.json')
.success(function(data) {
staff = data;
console.log(staff);
});
Which seems to return the data as I can see in my console but I can't get it to work (returns a blank array) with my existing function.
I have also tried to wrap the function in .finally after .success but then my function becomes undefined.
How can I use the API Data in the functions in my factory so I can get my page working as it was originally with the hard coded array?