I am currently working on an AngularJS application that retrieves data from a RESTful API using $resource. However, I have encountered an issue where the view is not updating with the data once it is received and assigned to my $scope.
As a beginner in AngularJS, there might be an error in my code that I am overlooking!
Below is my service implementation:
(function () {
'use strict';
var taxYearApp = angular.module('taxYearApp');
taxYearApp.factory('costService', ['$resource',
function ($resource) {
var theUrl = 'http://localhost/taxcalculator/api/CostApi/';
var CostResource = $resource(theUrl + ':taxYearID', { taxYearID: 'taxYearID' }, { 'update': { method: 'PUT' } });
return {
getCosts: function (taxYearID) {
return CostResource.query({ taxYearID: taxYearID });
}
};
}
]);
})();
This is how my controller is set up:
(function () {
"use strict";
var taxYearApp = angular.module('taxYearApp');
taxYearApp.controller('costController', ['$scope', 'costService',
function ($scope, costService) {
$scope.Costs = [];
var taxYearID = 1;
var promise = costService.getCosts(taxYearID);
promise.$promise.then(function () {
$scope.Costs = [promise];
});
}]);
})();
I have tried different approaches but none seem to solve the issue. Initially, I had
$scope.Costs = costService.getCosts(taxYearID);
.
Though I can see that $scope.Costs
does contain the desired data array, the view is not being updated accordingly.
Here is the snippet of my view:
<div ng-controller='costController'>
<div ng-repeat="Resource in Costs">
<form name='item_{{$index}}_form' novalidate>
<table>
<tr>
<td><h3>{{Resource.CostType}}</h3></td>
<td><input type="number" ng-model="Resource.CostAmount" required /></td>
</tr>
</table>
</form>
</div>
</div>
The object has been renamed to 'Resource' based on the JSON format returned by the promise.
If I manually request the webAPI, this is the JSON response I receive:
[
{
"CostID": 1,
"CostTitle": "Wage",
"GrossAmount": 10001,
"IsReadOnly": false
},
{
"CostID": 2,
"CostTitle": "Total Expenses",
"GrossAmount": 3000,
"IsReadOnly": false
}
]
Any advice on what could be causing the issue or how to refresh the $scope with asynchronous data would be greatly appreciated.