The ng-repeat directive fails to acknowledge changes in the model

I'm having trouble iterating over the properties of a model that I am updating. Below is the code snippet from my controller:

app.controller('VariantsController', ['$http', function($http){
    var ctrl = this;
    this.cars = []; // Eventually get the cars ...
    this.selected_car = null;

this.selectCar = function(car){
      ctrl.selected_car = car;
    }

When a user clicks on a "car" on the webpage, I update the selected_car property in the controller. The page then shows the name of the selected car correctly, but the ng-repeat directive does not iterate over the properties of selected_car.

Here's the relevant HTML (with variants as the alias for the controller):

<div ng-show="variants.selected_car">
  <h6>{{variants.selected_car.name}}</h6> <!-- Updates correctly -->
  <table class="table">
    <tr ng-repeat="(key,val) in variants.selected_car.specs"> <!-- Issue! Does not iterate -->
      <td>{{key}}</td>
      <td>{{val}}</td>
    </tr>
  </table>
</div>

I've reviewed this post: AngularJS: ng-repeat list is not updated when a model element is spliced from the model array, but the accepted answer mentions issues with operations outside of AngularJS. However, in my case, I believe updating the model from within the controller should not be problematic. How would I go about using $apply in this scenario without explicitly involving $scope?

The selected_car.specs object contains numerous keys:

{
   ...
   mileage: 13.53,
   mileage_city: 23,
   mileage_highway: 32,
   power: 220,
   ...
}

For further reference, here is a Plunker provided by @Phil: http://plnkr.co/edit/ULSr2Tk5D7phTYW0t7Ys?p=preview

Answer №1

Oh, the answer lies in the word "length"!

I believe that ng-repeat is trying to utilize the length attribute of the items it's looping through, and since you have a "length" property as well, it might be causing some issues with the iteration process.

To fix this issue, I suggest renaming your property to something like "body_length" or another unique name.

Check out the demo here

Answer №2

Verify the accuracy of your data input. It's possible that there could be an issue with accessing the object. Try outputting the object variants.selected_car.specs to check. I have prepared a demo on Plunker showcasing how to display a key-value table.

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5f50594b525f4c10544d7e0f100d1046">[email protected]</a>" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js" data-semver="1.3.4"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <table>
      <tr ng-repeat="(key, val) in {name:'John', age:25, gender:'boy'}">
        <td>{{key}}</td>
        <td>{{val}}</td>
      </tr>
    </table>
  </body>

</html>


var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.obj={name:'John', age:25, gender:'boy'}
});

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

Enhance efficiency of repetitive tasks involving accessing the Mongo database

Currently, I am developing a chat bot using MeteorJS/NodeJS, which engages with approximately 2,000 active users on a daily basis. Tracking the number of individuals who interact with the bot each day is made possible by storing their activity information ...

Enhancing web pages using PHP method progress tracking

I am in the process of creating a basic import wizard and I would like to incorporate a notification feature that displays the progress of each method. For example, I have the following methods: public function mainFunction() { $this->firstStep(); ...

Activating Cors Support on Firefox

When working with AngularJS, I wrote the following code to make an API call: $http({ method: 'GET', url: 'https://www.example.com/api/v1/page', params: 'limit=10, sort_by=created:desc', //h ...

Trouble with Displaying 3rd Level JQuery Dropdown Menu

Currently working on implementing a 3 level dropdown feature. I have been using a third-party responsive menu in Opencart and it's been working well. You can see a demo of it here: Unfortunately, Opencart does not natively support 3 level categories, ...

How can we ensure that the load more button disappears at the appropriate moment in this Vue 3 application?

I have been developing a news application with Vue 3 and the News API. I am currently implementing a feature for loading more articles on the page. Initially, there are 24 articles displayed, and if there are more articles available than the current numbe ...

Generate Address from Latitude and Longitude

For my project, I am trying to convert latitude and longitude coordinates into an address. While the Google Maps API is a potential solution, it requires an XML Response which complicates the process. I came across this helpful thread on Stack Overflow d ...

Having issues with Protractor unable to locate CKEditor during testing proceedings

When working with Protractor on a non-Angular page, I am trying to locate the CKEditor instance in order to update the data. The following code snippet works in the Chrome console: CKEDITOR.instances.html_editor.setData("Hello") However, when I attempt t ...

Establish a route nickname for files outside the project directory

I'm currently tackling a project that is divided into multiple angular projects. Within these projects, there are some services that are shared. Is there a way for me to incorporate these services into my project without encountering errors? /root / ...

After successfully creating an account, the displayName consistently appears as null

I have a Vue project that utilizes Firebase as the backend. User registration is done using email and password. Below is the method used in Firebase: firebase.auth() .createUserWithEmailAndPassword(this.user.email, this.user.password) . ...

Tips for declaring a data variable in Vue with the help of APIs

I'm currently working on a project where I am integrating movie data from an API (TMDb) using Vue Routers. I have a component named 'MovieList' where I am fetching data from the API. Below is the data structure: data() { return { mov ...

Challenges arise when attempting to accurately determine the pixel count of animated elements

I'm facing an issue with this code where it doesn't produce any result. The variable is needed since the number varies each time the user clicks. Is it not possible to define the number of pixels in this way? Your help is greatly appreciated. $( ...

Tutorial on packaging javascript with Parcel for Electron apps

I am currently utilizing Parcel with Electron by leveraging the resources provided at https://github.com/parro-it/electron-parcel-example. The specific project I am working on can be found at https://github.com/patrykkalinowski/dcs-frontlines-electron My ...

"Facing an issue with Google Chrome not refreshing the latest options in an HTML select dropdown list

Having trouble creating an offline HTML file that incorporates jQuery for the script. The page features a state select menu followed by a second menu for counties. When a state is selected, only the corresponding counties should display while others remai ...

JavaScript fails to load updated data that was most recently submitted

My recent query was regarding Javascript Form Submition. I am currently investigating why, after submitting the form, the create.js.erb file does not load the most recent data that was submitted. On submitting the data again, the table updates with the se ...

How to retrieve the first option selected in Material-UI React?

Hey there! I am currently working with React Material UI select. I have a question - how can I set the first option of items as selected without triggering the onChange method? When I change an option, it triggers the onChange method and adds an attribut ...

Using webpack without integrating babel can lead to compatibility issues with certain JavaScript

Struggling to create a basic demonstration using webpack and babel, I can't seem to pinpoint the issue. With webpack version 1.13.3 installed, attempting to add npm install --save-dev babel-core babel-preset-es2015 or npm install --save-dev babel-load ...

JavaScript has encountered an error due to exceeding the maximum call stack size, resulting in an un

I've been working on a project where I wanted to recreate the retro DVD logo bouncing around the screen but with a custom picture instead. However, I keep encountering an error message that's making it quite frustrating to work through. Here is ...

Multer is not recognizing the uploaded file and is returning req.file

This question has definitely been asked multiple times in the past, and I have attempted to implement various solutions without much success. Struggling to upload a file and read its size through Node has left me frustrated. Initially, I tried using the f ...

Printing in Firefox is ineffective, but functions smoothly in alternative browsers

I'm currently working on customizing some content specifically for printing, so I've implemented a hook import { useState } from 'react' const usePrint = () => { const [isPrinting, setIsPrinting] = useState(false) const hand ...

What is the best way to retrieve the result of a JavaScript function in an HTML form?

I'm currently developing a JavaScript app that involves selecting a random question from an array and combining it with a random object from another array. Here's a glimpse of how my app is structured: Array.prototype.random = function (length) ...