Reputation: 137
I am trying to return an array from a function once onClick is triggered. I see the values contained in the array in the console. But I don't see the values displayed on the HTML page.
The Controller:
$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 Page where values would be displayed:
<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>
Upvotes: 4
Views: 467
Reputation: 101
I recommend to use as controller syntax.The reason is angular does not reflect $scope array reference changes to the view properly because it generates new scope for ng-repeat i.e when you change the reference of $scope.chosenFilm ng-repeat will watch the old one at that time. For more detail : ng-repeat not updating on update of array. Your problem is excatly same as that one because you change chosenFilm reference after some time (promise resolving time) with response.data. If you dont like controller as syntax you can quickly use this one :
angular.extend($scope.chosenFilm, response.data);
Upvotes: 1
Reputation: 80
try this
$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!
});
}
Upvotes: 1
Reputation: 135
getSelectedFilm()
that calls the HTTP GET is not executed
It is inside insertFilm()
that is never called
Upvotes: 1
Reputation: 2930
This method returns promise value and it is asynchronous. Because of the you have to use htpp.get methods with callback functions.
As a result, with respect to your code you can use as
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
});
Upvotes: 1