我正在學習離子,我正在做一個教程。一切都很好,直到我創建了一個訪問web服務的工廠。如何將數據保存在角度工廠中的示波器
當我訪問範圍中的變量時,它們沒有被定義,或者它們就像我如何初始化變量。
這是代碼
Controller.js
angular.module('songhop.controllers', ['ionic', 'songhop.services'])
/*Controller for the discover page*/
.controller('DiscoverCtrl', function($scope, $timeout, User, Recommendations) {
// get our first songs
Recommendations.getNextSongs()
.then(function(){
$scope.currentSong = Recommendations.queue[0];
console.log($scope.currentSong);
});
console.log(Recommendations.queue);
console.log($scope.currentSong);
// Fired when a song is favorited or skiped
$scope.sendFeedback = function (bool){
Recommendations.nextSong();
// First add to favorites if they favorited
if (bool) User.addSongToFavorites($scope.currentSong);
$scope.currentSong.rated = bool;
$scope.currentSong.hide = true;
$timeout(function() {
$scope.currentSong = Recommendations.queue[0];
}, 250);
};
})
/*
Controller for the favorites page
*/
.controller('FavoritesCtrl', function($scope, User) {
// get the list of our favorites from the user service
$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){
// Make sure there is a song to add
if (!song) return false;
// Add to favorites array
o.favorites.unshift(song);
}
o.removeSongFromFavorites = function(song, index) {
// make sure there is a song to remove
if (!song) return false;
// remove to favorites array
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){
// merge data into the queue
p.queue = p.queue.concat(data);
});
};
p.nextSong = function() {
// pop the index 0 off
p.queue.shift();
// low on the queue? lets fill it up
if (p.queue.length <= 3) {
p.getNextSongs();
}
};
return p;
})
在我做了測試console.logs線,我得到第一個正確的數據。第二個是[],第三個是未定義的。
我不明白爲什麼
$scope.currentSong = Recommendations.queue[0];
沒有設置$ scope.currentSong變量應該因爲$範圍內的變量應該是全球性的東西,對不對?
你確定了''的$ scope.currentSong' console.log'了'promise'之前不執行該正在加載您的數據完成? –