AngularJS - using ng-repeat before initializing the scope variable

Currently, I have set up a md-tabs configuration, which is bound to $scope.selectedIndex for the purpose of being able to change it programmatically.

The process involves using a button to trigger a function that updates data. Subsequently, I modify $scope.selectedIndex to the desired tab number (in this case 3), leading to a change in the selected tab.

While everything seems to be working well, there is an issue where $scope.selectedIndex is being called before the completion of the .forEach() method, causing a ng-repeat not to function properly as it exits silently without any errors due to being undefined.

Button Commands: 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;
};

In essence, $scope.selectedIndex=3; results in the switch to Tab #4 (0-based).

Consequently, the subsequent ng-repeat operation fails to execute properly, likely due to the incomplete execution of .forEach(). Testing with $scope.seasons containing 2 empty indices confirms functionality.

<span ng-repeat="season in seasons">{{season.number}}</span>

Answer №1

It appears that the reason for this behavior is due to the asynchronous nature of the getShow function. To illustrate, consider the following snippet:

getShow(show.imdb_id, function (err, show) {
  show.episodes.forEach(function(array){
    $scope.seasons[array.season] = array;
    });
    $scope.selectedIndex=3;
});

Answer №2

The reason for the issue is that the data is not yet available, but the DOM is already loaded. A simple solution to this problem is to use the ng-if directive on the element and verify if the data is ready.

For example:

<span ng-if="season.number" ng-repeat="season in seasons">{{season.number}}</span>

Answer №3

After some trial and error, I finally found the solution to my issue. It turned out that the problem lied within the for() loop instead of the .forEach method. By simply adding a callback to the loop, I was able to change the tab successfully!

Original Code:

for (let i = 0; i < 11; i++) { }

Updated Code:

for (let i = 0; i < 11 || function(){ $scope.selectedIndex=3; }(); i++) { }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Loading FBX files with Textures in Three.js

After obtaining a fbx file with textures from this link, I attempted to open it using three.js: var loader = new THREE.FBXLoader(); loader.load('models/fbx/myfile.fbx', function(object) { scene.add(object); }, (ev) => { console.log(e ...

Changing the URI for the Apollo client instance

Currently, we are using Angular Apollo in one of our projects. The apollo client is being created like this: this.apollo.create({ link: this.httpLink.create({ uri: `${environment.apiBase}/graphql?access_token=${this.tokenService.token}`}), cache: new ...

Visualizing data with a grouped bar chart in D3.js

I am currently working on creating a vertical bar chart using D3.js, similar to the one shown in this https://i.sstatic.net/pig0g.gif (source: statcan.gc.ca) However, I am facing an issue as I am unable to display two sets of data for comparison. Follow ...

The rows in the React table are refusing to change color despite the styles being applied; instead, they are coming back

Hey there, Green Dev here! I've been working on a React table where I'm trying to conditionally change the row color. The styles are being passed in, but for some reason they return as undefined. Strangely enough, when I remove my logic and simpl ...

Utilize dynamic CSS application within an Angular application

In my Angular application, I dynamically load URLs inside an iframe and want to apply custom.css to the loaded URL once it's inside the iframe. I attempted using ng-init with angular-css-injector function in the iframe, but the CSS is not being applie ...

Tips for initializing store data in vuex before the component is rendered

Currently, I am utilizing Vuex to store a tree structure within the state property. This data is retrieved via an ajax call. The issue arises when the page renders before the variable in the state property has been fully populated. For example: // sth. ...

Difficulty encountered while developing personalized directives for image marquees in Angular

I have been trying to transfer a marquee of images into a custom directive. Originally, in my index file, I had a div structured like this: <div id="marquePic" style="width:90%"></div> and later in the script (end of body), I was implementing ...

Incorporate JavaScript code into an Angular UI-Router view

I can't seem to find an answer to this question anywhere, so I'm hoping someone here can help me out. In my AngularJS app, I am using ui-router to load multiple views into the same <ui-view> element. I am trying to implement Jquery UI&apos ...

Building a time series collection in MongoDB with Node.js

Are there any npm packages available for creating mongodb time series collections using node.js? I did not find any documentation related to this in the mongoose npm package. ...

Unable to retrieve JSON data in servlet

I am having trouble passing variables through JSON from JSP to a servlet using an ajax call. Despite my efforts, I am receiving null values on the servlet side. Can someone please assist me in identifying where I may have gone wrong or what I might have ov ...

Obtain the name of the object method from inside the method itself

Imagine having an object like this: var app = {} inside which there is a method: app = { initialize: function () { } } Is it possible to retrieve the name of the method 'initialize' from within the initialize() function without explicit ...

Creating a compact, production-ready code using the webapp generator in Gulp

I recently used the webapp generator to scaffold a project, but encountered an issue where the project only worked when accessed through localhost and not when opening the files directly in the browser with a file scheme. The URL http://localhost:9000/ cor ...

Unusual blue outline spotted on Firefox

Could you please review the following code snippet: http://www.jsfiddle.net/tt13/5CxPr/21 In Firefox, there is a strange blue border that appears when selecting multiple rows by pressing the ctrl button. However, this issue does not occur in Chrome. Thi ...

Strange behavior noticed with Bootstrap accordion

The current behavior of the product specs section is as expected. Clicking on group 1 shows its content, and when clicking on group 2, it minimizes group 1 and displays group 2. However, the issue arises with the next two categories, Usage and Installatio ...

Having difficulty obtaining accurate window height in Chrome

I am currently facing an issue with determining the accurate width and height of the browser window in Google Chrome. Interestingly, the size appears to be correct in Firefox, but I have not tested it on other browsers. Despite setting the doctype to !DOC ...

Oops! There was a validation error as the duration was not formatted as a number. Please make sure to provide a valid numerical value for the duration field

When attempting to update data from a MongoDB database and checking the results on Postman, an error is encountered. The error reads as follows: "Error: ValidationError: duration: Cast to Number failed for value \"NaN\" at path \"duration&bs ...

Animations experiencing delays on mobile Chrome

I am currently exploring the world of website animations. I have a version of the jsfiddle code linked below that is similar to what I am working on. The animations function perfectly when viewed on desktop, but when accessed on mobile - specifically on my ...

"Syncing Ajax requests with JSON in synchronous mode is not functioning properly when async is

The problem I am facing is with synchronous ajax: var result = false; $.ajax({ async: false, url: url, dataType: "json", success: function(data) { ...

Completed Animation with Callback in AngularJS CSS

Currently working with AngularJS and hoping to receive a notification upon completion of an animation. I am aware that this can be achieved with javascript animations such as myApp.animation(...), but I'm intrigued if there is an alternative method wi ...

What is the best way to fetch a UniqueID using document.getElementById()?

I am looking to utilize the __doPostBack JavaScript function. __doPostBack(obj.UniqueID,''); The challenge I'm facing is that I only have the ClientID of my object - ctl00_cpholder_myObjId document.getElementById("ctl00_cpholder_myOb ...