2017-08-02 118 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! 
    }); 
}