scope.membersWarnings in controller is always empty, but in service it gets the data from the server. Somehow my data from the server is lost between callback of get function in service and controller.
Controller:
AndreaApp.controller('MemberDetailController', ['$scope', '$rootScope','$http','$location','$routeParams','MemberService','MemberGroupsService','ArrivalsService','WarningsService','NotificationsService',function (scope,rootScope, http,location,routeParams,MemberService,MemberGroupsService,ArrivalsService,WarningsService,NotificationsService) {
scope.member = MemberService.get(routeParams.id);
scope.membersGroup = MemberService.membersGroup(routeParams.id);
scope.membersWarnings = WarningsService.get(routeParams.id);
scope.editMember = function(id){
location.path('/editMember/'+id);
}
scope.membersDocument = function(id){
location.path('/membersDocument/'+id);
}
scope.templates =
[ { name: 'packages.html', url: 'views/members/packages.html'},
{ name: 'notifications.html', url: 'views/members/notifications.html'},
{ name: 'warnings.html', url: 'views/members/warnings.html'},
{ name: 'arrivals.html', url: 'views/members/arrivals.html'} ];
scope.template = scope.templates[0];
scope.loadTemplate = function(templateId){
if(templateId == 3){
scope.arrivals = ArrivalsService.get(routeParams.id).arrivalsId;
console.log(scope.arrivals);
}
scope.template = scope.templates[templateId];
}}]);
WarningsService:
AndreaApp.service('WarningsService', function ($http,$q) {
var warnings = [];
this.save = function (warnings, memberId) {
$http.post('/api/warnings/new/member/'+memberId,
{
name: warnings.name,
description: warnings.description,
readed: false,
clanId: memberId
}).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
alert("Error occurred while adding a warning. HTTP Respone: " + status);
});
}
this.get = function (id) {
var deferred = $q.defer();
$http.get('/api/warnings/member/'+id).
success(function(data, status, headers, config) {
warnings.length = 0;
console.log(data);
for(var i = 0; i < data.length; i++){
warnings.push(data[i]);
}
deferred.resolve(data);
//data exists here, it is not empty
}).
error(function(data, status, headers, config) {
alert("HTTP status:" + status)
});
return deferred;
}});
scope.member = MemberService.get(routeParams.id);
Should be
MemberService.get(routeParams.id).then(function(data) {
scope.member = data;
});
This is because your get method is returning a promise, so once it is resolved, u can obtain the data.
Also, your get method needs to be changed to
return deferred.promise;