angular ng-repeat must be adjusted with modifications in the data received from a JSON file

Dealing with a JSON object that has incorrect data, my aim is to replace the existing value with one from a lookup table. However, I am unsure of how to swap out the data with values from the lookup table.

lookupTable = {
  "pizza": function() {
    console.log("food");
  },
  "house": function() {
    console.log("building");
  },
  "air": function() {
    console.log("nothing");
  }
};
$scope.value = lookupTable["pizza"]()

The HTML file contains:

<tr ng-repeat="x in names">
    <td>{{ x.lookupTable["pizza"]() }}</td> 

You can find my code at http://plnkr.co/edit/w4lOFVRo9vSi8vqfbpXV?p=preview

Would greatly appreciate any assistance!

Answer №1

There are a few issues in the code you provided:

  1. The functions within the `lookupTable` are not returning actual values, as mentioned in earlier responses.
  2. `lookupTable` is not a property of `$scope.names`, so referencing it with `x.lookupTable` is incorrect.

To address these problems, follow these steps:

  1. Ensure that the functions in `lookupTable` actually return values instead of just logging them to the console.
  2. Bind `lookupTable` to `$scope` correctly.
  3. Use `lookupTable` directly in the view since it is bound to `$scope`.

Here is the revised code snippet:

<div ng-app="myApp" ng-controller="customersCtrl">
  <table>
    <tr ng-repeat="x in names">
      <td>{{ lookupTable[x.Name]() }}</td> 
    </tr>
  </table>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
  $http.get("data.json")
  .then(function(response) {
    $scope.names = response.data.records;
  });


  $scope.lookupTable = {
    "pizza": function() {
      return 'food';
    },
    "house": function() {
      return 'building';
    },
    "air": function() {
      return "nothing";
    }
  };

});
</script>

Answer №2

It appears that your code is quite convoluted. I attempted to make some edits on your plunker, which might be easier to comprehend than trying to explain it.

<!DOCTYPE html>
<html>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="customersCtrl">

    <table>
      <tr ng-repeat="x in names">
        <td>{{ lookupTable[x.Name] }}</td> 
      </tr>
    </table>

  </div>

  <script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http) {
      $http.get("data.json")
        .then(function(response) {
          $scope.names = response.data.records;
      });

    
    lookupTable = {
      "pizza": "food",
      "house": "building",
      "air": "nothing"
    };
    $scope.lookupTable = lookupTable;
    $scope.value = lookupTable["pizza"]
    console.log(lookupTable["house"]) 
    });
  </script>

Answer №3

Upon reviewing your code, it appears unclear what you are attempting to accomplish.

The ng-repeat is generating three objects from the names list, however none of them contain a lookupTable property, causing {{ x.lookupTable["pizza"] }} to fail without throwing any errors.

To make it display properly, try binding to {{ x }} instead.

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

Tips for sorting through various elements or items

How can I improve my filtering function to select multiple items simultaneously, such as fruits and animals, or even 3+ items? Currently, it only allows selecting one item at a time. I attempted using , but it had bugs that displayed the text incorrectly. ...

Can Angular and Falcor work well together?

As I delve into learning about falcor, I have plans to incorporate it into my angular project. However, I am concerned about the lack of examples showcasing the integration of angular with falcor. Has anyone successfully implemented this combination befor ...

Consistent integration into React component

I'm currently working on an application using the React library, but my current challenge lies within JavaScript ES6 itself. Within a component (page) that I've created, I have implemented a custom Floating Action Button (FAB): class Page exten ...

In Bootstrap 5, clicking inside a dropdown should not cause it to open or close unexpectedly

Check out the code snippet below: <html> <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1f1212090e090f1c0d3d48534e534e">[email protected]</a>/d ...

Having trouble making the swing effect trigger on mouseover but not on page load

I am trying to achieve a swinging effect on mouseover only, not on page load. Below is the JS code I have: (function swing() { var ang = 20, dAng = 10, ddAng = .5, dir = 1, box = document.getElementById("box"); (function setAng(ang){ ...

Click event recursion occurs due to the use of $.post

I have a collection of product rows available for customers to select from. Each row is designated with the class "product-line". Upon clicking on a row, I aim to visually indicate its selection status by toggling the "product-checked" class, and subsequen ...

Swipe JS: tap on the edge to view the next item

Currently utilizing Swipe JS to generate a full-screen image gallery and aiming to incorporate the functionality of clicking on the left or right edge to navigate between the previous and next slides. An attempt was made to create absolutely positioned a ...

Error: undefined callback function in asynchronous parallel execution

Encountering the error message "callback is not defined" while attempting to utilize async.parallel has left me puzzled. Most examples of async.parallel demonstrate functions being inline, as shown in the async documentation here: https://caolan.github.io/ ...

Experiencing CORS issue on the frontend while using Django backend

I am currently accessing a Django REST POST API http://127.0.0.1:8000/api from my frontend located at http://127.0.0.1:5500/index.html. I have set up django-cors-headers and ensured that the frontend's image_upload.js, backend's settings.py, view ...

"Using only JavaScript to target and manipulate child elements within the

I'm currently transitioning from using jQuery to pure JavaScript, and I've just started but am encountering difficulties. Specifically, I am unsure how to select child elements in the DOM. <div class="row-button"> <input type="submi ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

Adding and Removing Attributes from Elements in AngularJS: A Step-by-Step Guide

<input name="name" type="text" ng-model="numbers" mandatory> Is there a way to dynamically remove and add the "mandatory" class in Angular JS? Please note that "mandatory" is a custom class that I have implemented. Thank you. ...

When a specific string is found in a textbox, trigger a function in JavaScript

Is there a way to search for a specific string within a large text box that contains 200 words? I would like to create a function that can color the string. For example, if the sentence "my dog is happy" is in the textbox and I want the word "dog" to be ...

Changing a URL parameter based on the element's width is a simple task when

I'm trying to display elements on a page by replacing a string in the URL parameter with the width of each element of a certain class. I'm new to JavaScript, so any help would be appreciated! Here's an example of the HTML for objects on the ...

Guide to setting up Date Range Validator within MVC 4

Is there a way to limit the user from inputting a date outside of a specific range in my MVC 4 application? I'd appreciate any advice on how to achieve this. ...

Looking to eliminate the usage of hostname, username, and password in PHP code

Here is some PHP code I need help with: <?php /* $host='127.0.0.1'; $uname='root'; $pwd='password'; $db="android"; */ require_once('dbConnect.php'); /* $con = mysql_connect($host,$uname,$pwd) or die("connect ...

Having difficulty sending Crypto JS encrypted data through an ajax request

I am attempting to secure a password by encrypting it and saving it on Mongo LAB through an Ajax post call. Unfortunately, I am encountering the following error: I have tried looking up the error message but I'm unable to understand why it is pointin ...

Exploring AngularJS navigation paths and searching capabilities

Currently, I am in the process of developing a small search engine which utilizes Angular and UI Router. My main objective right now is to determine the most efficient way to smoothly transition from the home page (where search submissions are made) to the ...

Obtaining the client's IP address using socket.io 2.0.3: a comprehensive guide

Currently, I am facing a challenge using socket.io v2.0.3 in my node.js server as I am unable to retrieve the client's IP address. Although there are several suggestions and techniques on platforms like stackoverflow, most of them are outdated and no ...

Error: Attempting to access the first element of a null property is not allowed

Currently, I am working on a NodeJS Project that utilizes Sails.js as the framework. The goal is to implement a permissions system where each group's permissions are set using Check Boxes within a form powered by AngularJS. However, upon clicking th ...