I'm trying to load data from JSON-file and displaying in my mobile app. But the problem is that I can't display the JSON datas on member-detail.html, where should be displayed datas of a specific user. But on member-index.html, where is the whole list of all users, I can get the json datas correctly.
I've two pages/templates:
member-detail.html: detail information about a single member. JSON data are not displayed correctly. On this page I actually only try to output following two expressions:
<h2>Name: {{member.firstname }} {{member.lastname}}</h2>
Here you can take a look at my file /data/members.json:
[
{
"id": 1,
"lastname": "Doe",
"firstname": "John",
}
]
I'm load the json data with a service about the $http.get function in file services.js. There are also two methods -> findAll for member-index.html (=is working correctly) and findById -> for member-detail.html (is working not correctly, access to json object does not working, look at this line: var member = members[memberId - 1]):
angular.module('myApp.services', [])
.factory('MemberService', function($http, $q) {
var members = $http.get("data/members.json").success(function(result){
return result.data;
});
return {
findAll: function() {
var deffered = $q.defer();
deffered.resolve(members);
return deffered.promise;
},
findById: function(memberId) {
var deferred = $q.defer();
//members[memberId - 1] --> THIS IS NOT WORKING
var member = members[memberId - 1];
deferred.resolve(member);
return deferred.promise;
},
}
});
Following controllers are used for member-detail.html:
.controller('MemberDetailCtrl', function($scope, $stateParams, MemberService) {
MemberService.findById($stateParams.memberId).then(function (member) {
$scope.member = member;
});
Result of my debbuging work is, that problem is on access to JSON-object in services.js on findById method. It's following line:
But I've no idea how I access the members variable correctly
You can find proper user by id in your members
array using forEach
:
var member = {};
angular.forEach(members, function (item) {
if ( item.id == memberId ) {
member = item;
return;
}
});
deferred.resolve(member);
return deferred.promise;