I study Ionic, and I am doing a textbook. Everything was fine until I created a factory that accessed the web service.
When I access variables in a scope, they are not defined or they just look like how I initialized the variable.
This is the code
Controller.js
angular.module('songhop.controllers', ['ionic', 'songhop.services'])
.controller('DiscoverCtrl', function($scope, $timeout, User, Recommendations) {
Recommendations.getNextSongs()
.then(function(){
$scope.currentSong = Recommendations.queue[0];
console.log($scope.currentSong);
});
console.log(Recommendations.queue);
console.log($scope.currentSong);
$scope.sendFeedback = function (bool){
Recommendations.nextSong();
if (bool) User.addSongToFavorites($scope.currentSong);
$scope.currentSong.rated = bool;
$scope.currentSong.hide = true;
$timeout(function() {
$scope.currentSong = Recommendations.queue[0];
}, 250);
};
})
.controller('FavoritesCtrl', function($scope, User) {
$scope.favorites = User.favorites;
$scope.removeSong = function(song, index) {
User.removeSongFromFavorites(song, index);
};
})
Service.js
angular.module('songhop.services', []).factory('User', function() {
var o = {
favorites: []
}
o.addSongToFavorites = function(song){
if (!song) return false;
o.favorites.unshift(song);
}
o.removeSongFromFavorites = function(song, index) {
if (!song) return false;
o.favorites.splice(index, 1);
}
return o
})
.factory('Recommendations', function($http, SERVER) {
var p = {
queue: []
};
p.getNextSongs = function() {
return $http({
method: 'GET',
url: SERVER.url + '/recommendations'
}).success(function(data){
p.queue = p.queue.concat(data);
});
};
p.nextSong = function() {
p.queue.shift();
if (p.queue.length <= 3) {
p.getNextSongs();
}
};
return p;
})
In the console.logs lines that I did for testing, I get the correct data in the first. The second is [], and the third is undefined.
I do not understand why
$scope.currentSong = Recommendations.queue[0];
doesn't set the $ scope.currentSong variable for what it should, since the $ scope variables must be global, right?