Reputation: 59
I have a md-tabs
setup, I have it binded to $scope.selectedIndex
so that I can change it by code when I need to.
I use a button, call my function that updates data, I then change $scope.selectedIndex
to the tab number needed (In this case 3) that will then change the selected tab.
All of that is fine, except it's calling $scope.selectedIndex
before .forEach()
call is finished, which results in a ng-repeat
not working as it exits silently with no errors since its not defined.
Button Calls:
ng-click="initTVShow(show)"
Function:
$scope.initTVShow = function(show) {
var rng = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 10; i++ )
rng += possible.charAt(Math.floor(Math.random() * possible.length));
$scope.show = show;
$scope.show_name = show.title.split(' ').join('') + "-" + rng;
$scope.poster = show.images.poster;
$scope.backdrop = show.images.poster;
$scope.seasons = [{},{}];
getShow(show.imdb_id, function (err, show) {
for (let i = 0; i < 10; i++) {
$scope.seasons[i] = show.episodes.filter((episode) => episode.season === i);
}
});
$scope.selectedIndex=3;
};
As you can see, $scope.selectedIndex=3;
basically changes to Tab #4 (0-based).
Then the following ng-repeat does not seem to work and most likely because .forEach hasn't finished yet. I tested with $scope.seasons with 2 empty index's to test and that works.
<span ng-repeat="season in seasons">{{season.number}}</span>
Upvotes: 0
Views: 71
Reputation: 59
I found the solution, it was actually just caused by the for() loop (Which pre-edit, was a .forEach), I simple added a callback to it, which changed the tab and it just WORKED!
Changed:
for (let i = 0; i < 11; i++) { }
To:
for (let i = 0; i < 11 || function(){ $scope.selectedIndex=3; }(); i++) { }
Upvotes: 0
Reputation: 71
It's because the data not ready and the DOM is.
you can solve it easily by adding ng-if
on the element and check if the data ready.
Like:<span ng-if="season.number" ng-repeat="season in seasons">{{season.number}}</span>
Upvotes: 1
Reputation: 790
I think that this is because the function getShow retrieves data asynchronously. Show it to us. Try this:
getShow(show.imdb_id, function (err, show) {
show.episodes.forEach(function(array){
$scope.seasons[array.season] = array;
});
$scope.selectedIndex=3;
});
Upvotes: 1