I have a script which gets data from a mysql database in a JSON-file. I would like to list these items and navigate to the details of the selected option. Everything works fine when I put the data statically in a variable, but it doesn’t work when I parse the json file with $http.get()
service.js
angular.module('starter.services', [])
.factory('RequestService',function(){
var requests = [
{
"id": "1",
"firstname": "Steve",
"lastname": "Jobs",
"allowance": "56",
"employeeid": "1",
"date": "2014-11-19 12:18:00",
"picture": "pic",
"startdate": "2014-11-12",
"enddate": "2014-11-12",
"type": "Ilness",
"reason": "My back hurts",
"notes": "The doctor said: 'You should rest!'",
"function": "Director",
"status": "Pending",
"comment": ""
}
];
return {
getRequests: function(){
console.log(requests);
return requests;
},
getRequest: function(id){
for(i=0;i<requests.length;i++){
if(requests[i].id == id){
return requests[i];
}
}
}
}
})
controllers.js
.controller('masterCtrl', function($scope, RequestService) {
$scope.requests = RequestService.getRequests();
})
.controller('detailsCtrl', function($scope, $stateParams, RequestService) {
$scope.request = RequestService.getRequest($stateParams.requestId);
})
So far, it works!
But if I replace the services.js file with the following, it doesn’t work anymore:
angular.module('starter.services', [])
.factory('RequestService', function($http) {
var requests = [];
return {
getRequests: function(){
return $http.get("url/to/getrequests.php").then(function(response){
requests = response.data;
console.log(requests);
return requests;
});
},
getRequest: function(id){
for(i=0;i<requests.length;i++){
if(requests[i].id == id){
return requests[i];
}
}
}
}
})
Can anyone help me please?
Thanks in advance!
Jan