Include and remove JSON data items within ng-repeat loop

I am in the process of creating a dynamic page where users can add multiple locations to their contact information. Currently, my code looks like this:

<div class="input-append" ng-repeat="location in newPartner.partner_location">
    <input class="input-large" type="text" ng-model="location">
    <button class="btn" type="button" ng-click="delLocation1({{$index}})">- {{$index}}</button>
</div>

<div class="input-append">
    <input class="input-large" type="text" ng-model="new_location">
    <button class="btn btn-primary" type="button" ng-click="addLocation1()">+</button>
</div>

This is the HTML structure and here is how the controller function operates:

$scope.newPartner = {'partner_name':'newname','partner_location':['X','Y','Z']};

$scope.addLocation1 = function() {
    $scope.newPartner.partner_location.push($scope.new_location);
    $scope.new_location = "";
}
$scope.delLocation1 = function(id) {
    $scope.newPartner.partner_location.splice(id, 1);
}

Initially, everything works fine. However, I encounter an issue when deleting and adding items simultaneously causing it to delete the wrong item. Can someone help me identify what went wrong? Thank you, Daniel!

Answer №1

To begin, remove {{}} from

ng-click="delLocation1({{$index}})"
. It should now be:

ng-click="delLocation1($index).

Secondly, I recommend adding a basic debugger to monitor the changes in our model when we add a new value:

<pre>{{newPartner.partner_location|json}}</pre>

Thirdly, consider updating the model to:

$scope.newPartner = {
        'partner_name': 'newname',
        'partner_location': [{value:'X'}, {value:'Y'}, {value:'Z'}]
    };

This modification is necessary as using this format: ['X','Y','Z'] prevents data manipulation.

Here is the working code:

HTML

<div ng-controller="fessCntrl">
    <div  ng-repeat="location in newPartner.partner_location">
        <input class="input-large" type="text" ng-model="location.value">
        <button class="btn" type="button" ng-click="delLocation1(newPartner.partner_location, $index)">{{$index}}</button>
    </div>
    <div class="input-append">
        <input class="input-large" type="text" ng-model="new_location">
        <button class="btn btn-primary" type="button" ng-click="addLocation1()">+</button>
    </div>        
        <pre>{{newPartner.partner_location|json}}</pre>
</div>

JS

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

fessmodule.controller('fessCntrl', function ($scope) {

    $scope.new_location = "empty";

    $scope.newPartner = {
        'partner_name': 'newname',
        'partner_location': [{value:'X'}, {value:'Y'}, {value:'Z'}]
    };

    $scope.addLocation1 = function () {
        $scope.newPartner.partner_location.push({value:$scope.new_location});
        $scope.new_location = "empty";
    }
    $scope.delLocation1 = function (locations, index) {
        locations.splice(index, 1);
    }
});

fessmodule.$inject = ['$scope'];

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

Is it possible to develop a function that can verify various input values and modify their appearance as needed?

I am currently working on creating a form and faced with the challenge of simplifying my code using a function. Specifically, I want to write JavaScript code that will check all input fields in the form to ensure they are filled. If any field is left emp ...

Employing a pair of interdependent v-select components to prevent any duplicate entries

I am currently working with two v-select boxes that share similar data. In my scenario, I extract attachments from an email and load them into an array. The issue I encountered is that the first select box should only allow the selection of one document, w ...

Tracking the progress of file uploads using Ajax

Currently, I am working on integrating file upload using Ajax and Php on my local Apache server. This is strong text. $('.uploadButton').click(function(){ var formData = new FormData($(this).closest('.fileUploadFor ...

Leveraging the power of Map and Sort to display the items containing image URLs alongside their respective timestamps

I'm diving into firebase and utilizing react, and currently I've come across this snippet of code: {photos.map(url => ( <div key={url} style={card}> <img src={url} style={image} /> <div s ...

"Exploring the Power of Angular Change Detection with Promises in a Hybrid

We are currently in the process of upgrading an AngularJS project to Angular 7 by following the recommended "hybrid" approach where both frameworks coexist. However, we have encountered some issues with change detection when dealing with native promises. T ...

Ways to retrieve the name of a JValue object

I have been working with Newtonsoft.Json to parse Json text, and I am trying to find a way to retrieve the name of a JToken or JValue object. For example, if "ChoiceId":865 is the value, I need to extract "ChoiceId". Despite spending hours on it, I haven&a ...

Loading a chunked polyfill file in webpack only when needed - a step-by-step guide

In order to prevent unnecessary loading of polyfills, it is recommended to add some logic in the <head> section (https://webpack.js.org/guides/shimming/) <script> var modernBrowser = ( 'fetch' in window && ...

Packager freezing after running npm audit and the component directory is nonfunctional

Greetings, To begin with, I would like to acknowledge that this issue may have been addressed in previous posts, but despite following suggestions on Stack Overflow and GitHub, I am still facing two specific problems. Here are the issues I am encounterin ...

Error encountered during AJAX POST request: NETWORK_ERR code XMLHttpRequest Exception 101 was raised while using an Android device

Here is the ajax post code that I am using: $.ajax({ type: "POST", url: "http://sampleurl", data: { 'email':$('#email').val(), 'password':$('#password').val(), }, cache: false, ...

How to retrieve the content/value from a textfield and checkbox using HTML

I'm encountering an issue with my HTML code where I am unable to extract data from the HTML file to TS. My goal is to store all the information and send it to my database. Here is a snippet of the HTML: <h3>Part 1 : General Information</h3 ...

How can we access state data in a Vuex component once it is mounted?

My goal is to initialize a Quill.js editor instance in a Vue component once it is loaded using the mounted() hook. However, I am facing an issue where I need to set the Quill's content using Quill.setContents() within the same mounted() hook with data ...

Is there a way to create a Captcha image from text using JavaScript in an HTML document?

As I work on creating a registration web page, ensuring security is key. That's why I'm looking for a way to generate captcha images for added protection. Any suggestions on how I can transform text into captcha images? ...

I am interested in utilizing props to send a variable to the view

Looking for assistance with passing the variable tmp_sell to my view. Here is the code: <p @tmp_sell="getTmpSell" >?</p> <input ref="q_subtotal" placeholder="Subtotal" @tmp_sell="getTmpSell" i ...

Looking to iterate through a dataframe and transform each row into a JSON object?

In the process of developing a function to transmit data to a remote server, I have come across a challenge. My current approach involves utilizing the pandas library to read and convert CSV file data into a dataframe. The next step is to iterate through t ...

The TableView is failing to display any data

Can anyone help me with a UITableView issue I'm facing? I am trying to populate the table with data obtained from a GET request. Strangely, setting a specific value in my numberOfRowsInSection method works fine (e.g., 8), but when I return the count o ...

The division element shifts to the left upon invoking the slideUp() function

I am currently working on a page that contains a form with two different sections - one is visible and the other is hidden. When the user clicks a button in the first section, it slides up using slideUp() while the hidden section slides down using slideDow ...

Angular/Ionic - How can I prevent my function from being called repeatedly while typing in an input field?

I am currently in the process of self-teaching how to construct an Angular/Ionic application. To store JSON, I am utilizing Backand and aiming to retrieve a random JSON value each time the page is refreshed. An issue I am facing is that the random call fu ...

Accessing data returned from JSON in JQuery beyond the code block required

Is there a way to access returned JSON data outside of the JQuery getJSON method? For example: var price = ""; $.getJSON("../JSONDeliveryPrice", null, function (data) { price = eval(data.price); }); console.log(price); Unfortunately, this code does not ...

how to transfer data from backend servlet to frontend javascript

Hey, I'm still learning about servlets so please excuse any confusion in my message! So basically, I'm trying to figure out how to pass a value from a servlet to JavaScript or even retrieve values from a servlet method within JavaScript. But I&ap ...

An error was encountered when attempting to use the 'await' syntax in a useEffect() function that called axios.get()

To avoid using .then(..), I have switched to utilizing await. I am making a call to a function that includes an Axios request and returns the data as response.data after awaiting for it. My functional component has a useEffect that is meant to initialize a ...