I have an angular service which contains two function to return an array of objects. The first returns the entire array, and the second a filtered array based on an ID. When I use the first function returning all the objects, data-binding works automatically and my front end updates as soon as I push a new object to the array. However when I use the function that returns a filtered list using underscore, my frontend doesn't update automatically.
I've done some research and the only thing similar to this that I have seen is in relation to async requests and using promises, but I'm not sure if this is appropriate in this case as I'm only using in service objects currently.
Service
angular.module('RankingsApp')
.service('results', function() {
var uid = 2;
var results = [
{
"id":1,
"fencer":1,
"competition":1,
"placing":1,
"points":50
}
];
this.getResults = function()
{
return results;
}
this.getResultsForCompetition = function (_id)
{
var resultsForCompetition = _.filter(results, function(x){ return x.competition == _id});
return resultsForCompetition;
};
this.insertResult = function (result) {
result.id = uid++;
results.push(result);
};
});
Controller
angular.module('RankingsApp')
.controller('CompetitionCtrl', function ($scope, competitions,fencers,results, $routeParams) {
$scope.getResults = function()
{
return results.getResultsForCompetition($routeParams.competitionID);
}
$scope.competition = competitions.getCompetition($routeParams.competitionID);
$scope.fencers = fencers.getFencers();
$scope.compResults = results.getResultsForCompetition($routeParams.competitionID);
function getNextPlacing()
{
return $scope.compResults.length + 1;
}
$scope.getFencerFromResult = function(result)
{
return fencers.getFencer(result.fencer);
}
$scope.getCompFromResult = function(result)
{
return competitions.getCompetition(result.competition);
}
$scope.addNewResult = function(fencer)
{
var result = { "fencer": fencer.id, "competition":$routeParams.competitionID, "placing": getNextPlacing(), "points":50 };
results.insertResult(result);
$scope.selectedFencer = null;
}
});
View
<table style="width: 100%">
<thead>
<tr>
<th>Placeing</th>
<th>Fencer</th>
<th>Comp</th>
<th>Points</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='result in compResults'>
<td>{{result.placing}}</td>
<td>{{getFencerFromResult(result).firstname}} {{getFencerFromResult(result).lastname}}</td>
<td>{{getCompFromResult(result).shortName}}</td>
<td>{{result.points}}</td>
<td><a>Edit</a></td>
</tr>
</tbody>
</table>