Everything works fine but I have problem getting source from service.
I have SERVICE code below.
app.factory('myService',
function($rootScope, ResourceData) {
var result = {};
var data = ResourceData.query();
result.getData = function() {
// problem here
}
return result;
});
And CONTROLLER contain code.
app.controller('myController', ['$scope', 'myService',
function myController($scope, myService) {
$scope.data = myService.getData();
});
My problem is if I have function in my SERVICE like this
result.getData = function() {
return data;
}
Everything works fine but I need to filter that data before I get it
If I change body like this I get an empty array the problem seems like it is from AngularJS.
If I create static array it works.
result.getData = function() {
var arr = [];
angular.forEach(data, function(item, key) {
// simple filter
if(item.ID > 10) {
return;
}
else {
arr.push(item);
}
});
return arr;
}
The result of “ResourceData.query()” is asynchronous:
When the page first loads, I’m guessing that the controller runs before the data is returned from the server, so the first time getData() is called,
datais probably not yet populated with any data, so you get an empty array.One solution to your problem would be to filter the data in the view/HTML with an Angular filter, rather than in the service.
Then in your controller: