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

The issue with the Z-index being ineffective is causing the button to appear behind a container in the HTML-CSS

I am currently using Metro CSS (Windows 8 style) and running into an issue. Within my container, there are alerts displayed in blue, and above that is 'IT-CENTER'. When I click on 'IT-CENTER', a button should appear, but it seems to be ...

Vue Router configuration functions properly when accessed through URL directly

I need guidance on how to handle the routing setup in this specific scenario: Below is the HTML structure that iterates through categories and items within those categories. The <router-view> is nested inside each category element, so when an item i ...

Vue's v-for loop updates all input fields instead of just one, ensuring consistency across the board

After spending hours on this issue, I am still stuck and unable to find a solution through Google search. The problem lies in my v-for loop where I am iterating over an array of objects. Each iteration renders input fields displaying the name and price of ...

Set YouTube Playlist to start from a random index when embedded

I've been trying to figure out how to set my embedded playlist to start with a random video. Here's what I attempted: <iframe src="https://www.youtube.com/embed/videoseries?list=PLPmj00V6sF0s0k3Homcg1jkP0mLjddPgJ&index=<?php print(ran ...

Implementing autocomplete feature with Bootstrap 3

I am currently implementing typeahead.js to create a dynamic search functionality. The goal is to search through a JSON file and display the results on the screen. To achieve this, I have prepared a JSON file that contains all the devices that will be sea ...

Looking to implement URL navigation based on a selected value from a dropdown menu when the onClick button is pressed

I am struggling with getting the Go Button to navigate to a specific URL like "&age=10" without selecting it. I require assistance with creating code that will allow me to redirect to the URL with post URL variables for my WordPress site. ...

Patience is key when it comes to waiting for a function to finish before moving on to the next step

I'm delving into the world of node js and currently immersing myself in the concepts of promises and async/await. Here's a code snippet I've been experimenting with, but I can't quite figure out how to ensure that the code waits until t ...

Property of object (TS) cannot be accessed

My question relates to a piece of TypeScript code Here is the code snippet: export function load_form_actions() { $('#step_2_form').on('ajax:before', function(data) { $('#step_2_submit_btn').hide(); $(&ap ...

Is there a way to verify if a user has selected the correct answer in a quiz program?

Here we have code segments in ajax, javascript, html, and an xml file. I'm looking to calculate the total score based on user input to determine if they selected the correct answers for a test. I've attempted to figure this out, but I'm str ...

"Utilize the parent component's functionality by extending/inheriting it

export default function PageTemplate() { return ( <div className="layout"> <LeftMenu /> <div className="content"> <TopMenu /> <div id="other-contents"> ...

Angular's ng-submit directive does not use the most up-to-date scope available

I'm currently learning Angular and have been struggling with a particular issue. I have created a form to edit user details. Upon page load, I make an AJAX call to fetch the data of the selected user and populate the scope with the values. Initially, ...

ng-repeat count filter not refreshing multiple times

Looking at a list with filters attached, I am trying to count the items and show a message if there are no items... <li ng-repeat="item in items = (items | sortWithTab:tab | filter:search")> {{ item.name }} </li> <div ng-if="items.lengt ...

Steps to create a conditional AJAX request triggered by the onbeforeload event depending on the value of a variable

My website script tracks user login status in real time using "onbeforeunload", ajax, and logout.php. This method updates the MySQL database with a value of 1 or 0 to indicate if a user is logged in. Unlike monitoring cookies, this approach allows accurate ...

Creating a New Line in JSON Format Using Flask Python and Displaying it as HTML

I've been struggling to properly format JSON with new lines, but all my attempts have failed. from flask import * import json app = Flask(__name__) @app.route("/user/", methods=["GET"]) def user(): datajson = {"Author&q ...

Troubleshooting Problem with Ionic Android Emulator

When using my app, I access an external API to retrieve data. The strange thing is that everything works fine on the browser and the built version, but when I try it on the emulator, the request gets rejected. However, when I test the app on an actual devi ...

What is the best way to highlight and extract only the white-coded texts on VSCode to facilitate the process of translating webpages manually?

Currently, I'm engaged in a project where my task involves duplicating an entire website using HTTrack. However, I only need to copy the main page and web pages that are one link deep. Upon copying the website, my next challenge is to translate all of ...

Issues arise with the loading of models while attempting to utilize Mocha testing

I'm currently in the process of using mocha for testing my express application. In terms of folder structure, it looks like this: myapp |-app |--models |-test |--mocha-blanket.js |--mocha |--karma |-server.js The server.js file serves as my express ...

Tips for accessing an Angular service from different Angular controllers

I am a beginner with angular js and I am currently exploring ways to call the service provided in the code snippet below from a controller. The service is defined as follows. app.factory('myappFactory', ['$http', function($http) { v ...

Add a new class to an element located in a separate div using JavaScript

$(document).ready(function() { $('.btn').click(function() { $(this).parent().addClass('show'); }); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div clas ...

"I am looking for a way to retrieve dynamic data from a (click) event in Angular. Can

Within my component, I have a video loaded in an i tag on a click event. The challenge is accessing the video ID from the video.component.ts file in order to dynamically load a new video. The solution has been elusive so far. <li *ngFor="let video of c ...