2017-08-02 116 views
4

我正在嘗試返回一個函數的數組一次onClick被觸發。我在控制檯中看到數組中包含的值。但是我看不到HTML頁面上顯示的值。

控制器:

$scope.chosenFilm = []; //The array where values are stored 

    //onClick function 
    $scope.insertFilm = function() { 
    console.log("Film saved in watch list!"); 
    getSelectedFilm(); //Call function 
} 

function getSelectedFilm() { 
    return $http.get('/watch-list').then(function(response) { 
     $scope.chosenFilm = response.data;  
     $log.info($scope.chosenFilm[0]); // Values displayed in console! 
     return $scope.chosenFilm; 
     }); 
} 

HTML頁,其中將顯示值:

<div class="container"> 
     <table class="table"> 
      <thead> 
      <tr> 
       <th>Film</th> 
       <th>Poster</th> 
       <th>Overview</th> 
       <th>Genres</th> 
       <th>Release</th> 
      </tr> 
      </thead> 
      <tbody> 
      <tr ng-repeat="film in chosenFilm"> 
       <td>{{film.title}}</td> 
       <td><img ng-src="{{film.poster}}"></td> 
       <td>{{film.overview}}</td> 
       <td>{{film.genres}}</td> 
       <td>{{film.release | date: "dd.MM.y" : UTC+00:00 }}</td> 
      </tr> 
      </tbody> 
     </table> 
</div> 
+1

你說的是HTML的地方使用哪個控制器? –

+0

嘗試在'http'服務之前移除'return'。也不需要返回數組。只要足夠'$ scope.chosenFilm = response.data;' –

+0

@Hadi,但這在這種情況下不是問題。它不應該干擾元素的渲染 – lealceldeiro

回答

1

此方法返回承諾值,它是異步的。因爲你必須使用帶回調函數的htpp.get方法。

其結果是,相對於你的代碼,你可以爲

function getSelectedFilm() { 
    $http.get('/watch-list').then(function(response) { 
     $scope.chosenFilm = response.data;  
     $log.info($scope.chosenFilm[0]); // Values displayed in console! 
     $scope.chosenFilm; 
     }) 
.then (() => { 
console.log($scope.chosenFile); 
......something else...; // you can see the data 
}); 
+0

由於異步方法,它不能順序工作。如果你想要一些連續的結果,你可以使用.then((result)=> {..something else ...})來使用promise值。然後().... –

+0

console.log($ scope.chosenFile);似乎在控制檯中返回undefined。 –

+0

請發送路徑給出的信息,我可以給你發送完整的解決方案... –

1

getSelectedFilm()調用不執行

的HTTP GET它裏面insertFilm()是從來沒有所謂的

+0

getSelectedFilm( )仍然由insertFilm()調用。我測試了它,並獲得了控制檯中顯示的值,但沒有顯示在頁面上。 insertFilm()是onClick函數。 –

1

我用建議使用控制器語法。原因是角度沒有正確反映$ scope數組引用對視圖的更改,因爲它爲ng-repeat生成新的作用域,即當您更改$ scope.chosenFilm ng-重複將在那個時候觀看舊的。 欲瞭解更多詳情: ng-repeat not updating on update of array。 您的問題與該問題非常相似,因爲您在響應數據一段時間後(改變解析時間)更改了selectedFilm引用。如果你不喜歡控制器的語法就可以快速使用這一個:

angular.extend($scope.chosenFilm, response.data); 
1

試試這個

$scope.chosenFilm = []; //The array where values are stored 

//onClick function 
$scope.insertFilm = function() { 
console.log("Film saved in watch list!"); 
$http.get('/watch-list') 
.then(function(response) { 
     $scope.chosenFilm = response.data;  
     $log.info($scope.chosenFilm[0]); // Values displayed in console! 
    }); 
}