2015-06-21 41 views
0

我正在爲此苦苦掙扎了一段時間,但無法弄清楚。我擁有的是主控制器,工廠和服務,並且我試圖將服務中的數組存儲到控制器中的$ scope。在視圖上項目單擊控制器此功能被觸發:控制器調用上的角度填充和返回服務變量

$scope.getSongsInPlaylist = function() 
        { 
         var playlistId = this.item.idPlayliste;       
         $scope.Mp3Files = songInPlaylistFactory.getSongsForPlaylist(playlistId); 

        } 

這工作好了,這個功能從視圖中檢索項目,並將該項目的ID在服務的功能。 比我的服務,我有這樣的代碼:

var Songs = [ ]; 
    this.getSongsForPlaylist = function (id) 
         { 
          for (var i = 0; i < SongIsOnPlaylist.length; i++) 
          { 
           if(SongIsOnPlaylist[i].idPlayliste == id) 
           {         
            dataFactory.getDataById(mp3fileUrl, SongIsOnPlaylist[i].idPjesme) 
            .success(function (data) { 
             Songs.push(data); 
             alert(Songs[0].naslovPjesme);//Alert one        
            });       
           }        
          } 
          alert(Songs[0]);// Alert two 
          return Songs;       
         } 

的DataFactory是我廠與在後端API進行通信,並且也可以。 var歌曲定義如下:var Songs = []; SongIsOnPlaylist中充滿了數據。

當我觸發這個,警告兩個給我不確定,並提醒一個給我我的歌曲的第一首歌曲的名稱。這意味着VAR歌曲充滿了數據,但是當我想讓它返回到控制器時它的空...

我在這裏做錯了什麼,我將不勝感激任何幫助?

+0

歌是出了dataFactory的範圍,你不能在那裏使用 –

+0

歌曲是在這個服務中定義的,而不是在dataFactory中定義的,如果你有這個想法? –

回答

1

首先它看起來像你的dataFactory.getDataById是異步調用。 正因爲如此,實際發生的情況是,當您的所有異步調用返回時,它會在填充之前返回一個空的歌曲

爲了解決這個我會建議使用無極庫像bluebird做這樣的事情:

// note that now your service will return a promise 
this.getSongsForPlaylist = function (id) { 
    return new Promise(function(resolve, reject) { 

    var promises = []; 
    // here in your loop just populate an array with your promises 
    for (var i = 0; i < SongIsOnPlaylist.length; i++){ 
     if(SongIsOnPlaylist[i].idPlayliste == id){         
     promises.push(dataFactory.getDataById(mp3fileUrl, SongIsOnPlaylist[i].idPjesme)) 
     }        
    } 
    // now use the library to resolve all promises 
    Promise.all(promises).then(function (results) { 
     //HERE YOU WILL GET the results off all your async calls 
     // parse the results 
     // prepare the array with songs 
     // and call 
     resolve(Songs); 
    }); 
    }); 

} 

然後你會使用這樣的服務:

$scope.getSongsInPlaylist = function() { 
    var playlistId = this.item.idPlayliste;       
    songInPlaylistFactory.getSongsForPlaylist(playlistId) 
    .then(function(Songs){ 
    $scope.Mp3Files = Songs 
    }) 
    .error(function(err){ 
    //here handle any error 
    }); 
} 
+0

非常感謝,你讓我的一天更好:) –

+0

歡迎您;-) – szydan