Having difficulty modifying elements within an array using AngularJS techniques

Hey there, I'm just starting to dip my toes into AngularJS. I'm attempting to add and remove elements in an array, but I'm struggling to achieve the desired outcome.

Here's the JSON structure I'm working with:

$scope.masters = [
  {
    "name": "Wittgenstein",
    "thoughts": ["thought 1", "thought 2", "thought 3"]
  },
  {
    "name": "King",
    "thoughts": ["thought 1", "thought 2", "thought 3"]
  }
];

Check out the Plunker here:

Plunker

Any suggestions or feedback would be greatly appreciated. Thanks!

Answer №1

According to suggestions by @Mathew, it is recommended to incorporate the use of $index in the following manner:

JavaScript code:

$scope.input = [];

$scope.add = function(i) { // receiving index as param
    $scope.masters[i].thoughts.push($scope.input[i]);
    $scope.input[i] = '';
};

HTML code:

<div ng-repeat="master in masters">
  <h1>{{ master.name }}</h1>
  <ul>
    <li ng-repeat="thought in master.thoughts">
      {{ thought }} <button ng-click="remove($index)">Remove</button>
    </li>
  </ul>
  <input type="text" ng-model="input[$index]">
  <button type="submit" ng-click="add($index)">Add</button>
</div>

For a functional example, check out this Plunker demonstration

Answer №2

To successfully remove a thought from a specific master, you must ensure to mention the index of that master in your code. Consider the following example within the remove function:

$scope.masters[masterIndex].thoughts.splice(index, 1);

Remember, the variable 'masterIndex' should represent the index of the master you wish to edit.

Answer №3

One issue is that the add and remove functions require the index of the masters to be passed to them. This is because you are using:

$scope.masters.thoughts.splice(index, 1);

Since masters is an Array, you need to specify which object inside the Array to select. For example:

$scope.remove = function(masterIndex, thoughtsIndex) {
    $scope.masters[masterIndex].thoughts.splice(thoughtsIndex, 1);
};

To make this work in your HTML, you need to use the parent index within the inner ng-repeat loop:

<div ng-repeat="master in masters">
    <h1>{{ master.name }}</h1>
    <ul>
        <li ng-repeat="thought in master.thoughts">
            {{ thought }}
            <button ng-click="remove($patent.index, $index)">
                Remove
            </button>
        </li>
  </ul>
  <input type="text" ng-model="input">
  <button type="submit" ng-click="add($index)">Add</button>
</div>

In the Add function, you will also need to receive the $index of the masters array in a similar way.

Answer №4

This is the updated version of your plnkr.

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddbcb3baa8b1bcaff3b7ae9decf3e9f3ed">[email protected]</a>" data-semver="1.4.0" src="https://code.angularjs.org/1.4.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="demoController">

    <div ng-repeat="master in masters track by $index">
      <h1>{{ master.name }}</h1>
      <ul>
        <li ng-repeat="thought in master.thoughts track by $index">
          {{ thought }} <button ng-click="remove(master, $index)">Remove</button>
        </li>
      </ul>
      <input type="text" ng-model="input[$index]">
      <button type="submit" ng-click="add($index)">Add</button>
    </div>

  </body>
</html>

I have made some enhancements to ensure that the remove function processes the correct master by including it as an argument. This guarantees accuracy when splicing since JavaScript arrays are passed by reference. See the updated angular controller below.

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

app.controller('demoController', ['$scope', function ($scope) { 

  $scope.input = [];

  $scope.masters = [ {
    "name": "Wittgenstein",
    "thoughts": ["thought 1", "thought 2", "thought 3"]
  }, {
    "name": "King",
    "thoughts": ["thought 1", "thought 2", "thought 3"]
  }];

  $scope.add = function(index) {
     $scope.masters[index].thoughts.push($scope.input[index]);
     $scope.input[index] = '';
  };

  $scope.remove = function(master, index) {
    master.thoughts.splice(index, 1);
  };
}]);

The add function may encounter a binding issue rather than a functionality problem with not fetching the input model's value correctly.

Here's the Updated Plunkr

I trust this information proves helpful.

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

The perfect way to override jest mocks that are specified in the "__mocks__" directory

Within the module fetchStuff, I have a mock function named registerAccount that is responsible for fetching data from an API. To test this mock function, I've created a mock file called __mocks__/fetchStuff.ts. Everything seems to be functioning corre ...

What is the best way to calculate the total number of results using ajax?

Encountering an issue with the total count of ajax search results. Getting an error message "Method Illuminate\Database\Eloquent\Collection::total does not exist." when using directives, for example: <div class="searched-item"&g ...

What is the process for running a JavaScript file within another JavaScript file?

I am facing an issue with creating a JavaScript file that can execute multiple other JS files, but I am unable to get it working. Is there a method to call and run a JavaScript file within another JavaScript file? For instance: function executeJSFile() { ...

The disappearing drop-down form issue arises when utilizing AJAX to fetch data from a MySQL database using a PHP file

Using AJAX to fetch data from a MySQL database via a PHP file and display it in a dropdown menu based on the user's initial selection is working smoothly. The second dropdown populates correctly as intended. However, an issue arises when an option is ...

Discovering the unique identifier of an item in Node.js is simple with these steps

I have a delete API which requires the item's unique ID to be passed in for deletion. How can I capture the ID of the item being deleted and send it to the API? Here is the API: app.post("/delete_product", function (req, res) { var data = { ...

keep information separate from a react component and generate state based on it

Is it considered acceptable to store data outside of a react component and update it from within the component in order to derive state? This method could be useful for managing complex deep-nested states. import React from "react"; let globalSt ...

angular establish Header when an image is loaded

Every request to authenticate with the server requires a special value in the HTTP header. The code I am currently using is as follows: <img ng-if="content.image" src="{{img(content.image)}}"> and var app = angular.module('myApp', []); ...

What is the simplest method for showcasing an image after it has been created on a node.js web server with the help of express?

After developing a mini web server with node.js and the express 4 framework, I implemented a feature where users can upload image files from the main page. The uploaded images are sent to the server through the multer middleware, processed by a python scri ...

The creation of an indexedDB database and the addition of content encountered an error while trying to perform a 'transaction' on the IDBDatabase

I am relatively new to using IndexedDB and have successfully created a database. However, I am encountering an error when trying to add content to it. The specific error message reads: Uncaught NotFoundError: Failed to execute 'transaction' on ...

Sending a variable from the server to the client using express rendering in Node.js

When using a Node.js express server, I am attempting to pass a variable to the index.ejs file on the client side. In my server code, I have added: res.render("dashboard/index", { hidePayment: true }); The problem arises when trying to access the hidePayme ...

Generate radio buttons in a model loop in Vue.js based on names automatically

I am attempting to generate a model for each radio button using the inputname as the identifier. My approach involves looping through the array of objects to identify instances where more than one inputname is present, and then converting this value into a ...

In PHP, leverage the value that comes after the hash symbol in the URL

Understanding that the URL after the # is not typically sent to the server, I am facing a challenge. I have a webpage displaying 16 database results with a "load more" button for the next set of 16. My goal is to find a solution where if a user navigates ...

Implement a fresh variable scope for an entity

Utilizing the following script enables jQueryUI's autocomplete to function with xeditable, producing the desired outcome: $(function(){ dialog.find('a.car').xEdit('autocomplete',{name:'carName', title:'C ...

Guide on retrieving key-value pairs from a JSON reply

While attempting to extract the sid and date_created values from the JSON response received from Twilio after sending a text message, I encountered an issue where they were always returning as undefined. I experimented with using body.['sid'] an ...

Is it possible to verify a URL using an if/else statement?

I need to verify a submitted URL by excluding any additional paths from it. Here is the URL that the user submitted: const inputUrl = document.getElementById("inputVal").value; If the user submits 'http://example.com/faq', I want to write an i ...

Retrieve the pdf document from the server's response

Currently, I am working on a project where I am using PHP Laravel to create a docx file, converting it to PDF, and saving it in a public server folder. Afterwards, I send the file as a response to the client. On the client side, I am attempting to downloa ...

Add a CSS class to an innerHTML element just a single time

I currently have 2 files available: data.php page.php The data.php file is responsible for fetching a row from a SQL database and sending it to the page.php file. Within the page.php file, there is a JavaScript script that receives this row through AJAX ...

Utilize A-frame image resources within JavaScript code

Currently, I am utilizing an image as a texture in multiple instances. Once through the material component and another time within a custom component where I am using THREE.TextureLoader(), resulting in the application loading the image two times. I believ ...

Attempting to remove options in a Multiple Choice scenario by selecting the X icon beside each one

I'm working on a multiple choice quiz and I'd like to add a button or icon resembling X in front of each option (even in front of the radio button), so that when I click on it, only that specific option is deleted. How can I achieve this? For in ...

Using the absolute positioning property in CSS is causing the text box to move downwards

I created a prototype using material-UI chips. Upon clicking the Test IPA, the textbox should appear right below the text Test IPA. In the prototype, it does show up below the text but when I include other functionalities, it ends up at the bottom instea ...