Issues arise when attempting to generate multiple instances of textboxes and textbox groups dynamically within AngularJS

Here is the code snippet:

<body>
<div ng-app=''>
    <div ng-controller="questionCtrl">
        <div>
            <ul />
            <li ng-repeat="prdElement in palletElement">
                <input type="text" ng-model="prdElement.name" placeholder="Name" required />
                <ul>
                    <li ng-repeat="elemnt in prdElement.children">

                        <div>
                            <span>
                                <input type="text" ng-model="elemnt.name" placeholder="Name" required />
                            </span>
                            <span ng-hide="elemnt.length == 1">
                                <a href ng-click="prdElement.splice($index, 1)">remove</a>
                            </span>
                        </div>
                        <hr />
                    </li>
                    <li>
                        <a href ng-click="newPrdItem($event)">New Item</a>
                    </li>
                </ul>
            </li>


        </div>
        <div>
            <button ng-click="showitems($event)">Submit</button>
        </div>
        <div id="displayitems" style="visibility:hidden;">
            {{prdElement}}
        </div>
    </div>
</div>

    function questionCtrl($scope){
var counter=0;

$scope.palletElement = [{
    name: 'Pallet 1',
    children: [{
        name: '11',
    }, {
        name: '12',
    }]
}, {
    name: 'Pallet 2',
    children: [{
        name: '21'
    }, {
        name: '22'
    }]
}]



$scope.newPrdItem = function ($event) {
    counter++;
    $scope.prdElement.children.push({ id: counter, name: ''});
    $event.preventDefault();
}

$scope.showitems = function($event){
    $('#displayitems').css('visibility','none');
}

}

JSFiddle everything seems fine but there's an issue with adding and removing elements functionality

Answer №1

In your code, you have a variable called $scope.palletElement which is an array containing objects with a children property at each position. The issue arises in the $scope.newPrdItem function where you are incorrectly trying to access the children property of the entire array instead of accessing it from the object at a specific index within the array.

To fix this issue, you should update your function like so:

$scope.prdElement[0].children.push({ id: counter, name: ''});
$scope.prdElement[1].children.push({ id: counter, name: ''});

Instead of:

$scope.prdElement.children.push({ id: counter, name: ''});

Additionally, in your remove function, you are using the splice method on an object rather than an array. You should modify this part of the code:

prdElement.children.splice($index, 1)

Instead of:

prdElement.splice($index, 1)

The complete revised code can be found in this JSFiddle link: JSFiddle

js

function questionCtrl($scope){
    var counter=0;

    $scope.palletElement = [{
        name: 'Pallet 1',
        children: [{
            name: '11',
        }, {
            name: '12',
        }]
    }, {
        name: 'Pallet 2',
        children: [{
            name: '21'
        }, {
            name: '22'
        }]
    }]



    $scope.newPrdItem = function (prdElement, $event) {
        counter++;
        prdElement.children.push({ id: counter, name: '', inline: true });
        $event.preventDefault();
    }

    $scope.showitems = function($event){
        $('#displayitems').css('visibility','none');
    }
}

HTML

<body>
    <div ng-app=''>
        <div ng-controller="questionCtrl">
            <div>
                <ul />
                <li ng-repeat="prdElement in palletElement">
                    <input type="text" ng-model="prdElement.name" placeholder="Name" required />
                    <ul>
                        <li ng-repeat="elemnt in prdElement.children">

                            <div>
                                <span>
                                    <input type="text" ng-model="elemnt.name" placeholder="Name" required />
                                </span>
                                <span ng-hide="elemnt.length == 1">
                                    <a href ng-click="prdElement.children.splice($index, 1)">remove</a>
                                </span>
                            </div>
                            <hr />
                        </li>
                        <li>
                            <a href ng-click="newPrdItem(prdElement,$event)">New Item</a>
                        </li>
                    </ul>
                </li>
            </div>
            <div>
                <button ng-click="showitems($event)">Submit</button>
            </div>
            <div id="displayitems" style="visibility:hidden;">
                {{prdElement}}
            </div>
        </div>
    </div>
</body>

I hope these explanations and code modifications help solve the issues in your code.

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

Encountering a 400 Bad Request error when attempting to post data, but still managing to successfully save

CODE OPERATION: STORING USER DATA IN DATABASE AS A NEW APP USER REGISTRATION. ISSUE: DATA IS SAVED, BUT RECEIVING "400 BAD REQUEST" AND ERROR MESSAGE IN CONSOLE ERROR: "Cannot save() the same document multiple times in parallel" SCRIPT (GENERATING JWT T ...

Dynamically load values for AJAX functions

I am working on a dynamic list of strings that are generated through an AJAX call. Here is the function I am using: function updateIngredients(boxId, prodid) { $.ajax({ type: "GET", url: "/Products/FetchBoxIngredients?idbox ...

The Vue.js instance is referencing the "options" property or method during render, but it has not been defined

Working with Vue.js (and Inertia.js), I encountered an issue while trying to build a select element in my form. After compiling, the select appears empty, and the developer console in the web browser shows the following error: The property or method "opti ...

What is the best way to configure nodejs and expressjs for rendering multiple html files with angularjs integration?

I am currently utilizing the following code snippet: app.use(express.static(__dirname + '/public')); to designate the static folder for a MEAN application. I require multiple html files that incorporate angularjs (not angular2). However, the is ...

Achieve the central element while scrolling on the window

What am I doing wrong? I've been attempting to target the #second element on scroll Here is an example with console.log CODEPEN EXAMPLE $(window).scroll(function(){ var section = $("#second").offset().left, scrollXpos = $( ...

Pulling down the data with Ajax "GET"

When a user clicks on a button, a zip file will be downloaded. I have the necessary components in place, but I am struggling to ensure they work together seamlessly. The "GET" call will retrieve byte content with the content type specified as application/ ...

Filtering and searching within a diverse HTML table array

Looking to implement a filter feature in a table with a complex array structure: let items [ { "_resource":{ "values":[null, undefined, true, 'foobar', {'amount': 1111, 'isValid': true} , ...

Updating the image sources of a group of image tags with a predetermined list

Looking to update a series of image source references within a specific div tag. For example: <!-- language-all: lang-html --> <div id="Listofimages"> <img src="images\2page_img_3.jpg"> <img src="images\2page_img_3 ...

How come I am unable to reach the window in my Next.js application's '_app.js' file?

In my Next.js application, I am trying to implement a feature where the app loads and then checks for network access using a custom modal dialog that alerts the user if they lose internet connection. I have set up an _app.js file in my application to estab ...

Instructions for selecting a checkbox using boolean values

According to the HTML specification, you should use the checked attribute in the <input type="checkbox"> tag to indicate that it is checked. However, I only have a boolean value of either true or false. Unfortunately, I am unable to manipulate the b ...

Root scope digest trigger delay

When invoking $scope.$apply() ten times consecutively, it is expected that ten root scope digests will occur. If the call to $scope.$apply() is debounced so that the trailing call always completes, can we assume that the final state of the application rem ...

Using Stringify to modify the value of a particular array in Local Storage

Uncertain of the accuracy of my question, but I am attempting to modify a value within a localstorage array. This is what my localstorage currently contains: [{"id":"item-1","href":"google.com","icon":"google.com"}, {"id":"item-2","href":"youtube.com","i ...

Is there a way to retrieve the day of the week based on the date provided by the user

function retrieveWeekday() { var input = document.getElementById("input"); } <form> <input type="date" placeholder="dd:mm:yy" id="input"/> <input type="button" value="get weekday" onclick="retrieveWeekday()"/> ...

Using jQuery to add emoticons to a div element

I am currently developing a small chat application and I would like to incorporate emojis into it. My goal is to allow users to click on an emoji, which will then appear in the text area where they type their message. When a user clicks on "select," I want ...

Configuring a JavaScript calendar with custom margins

Having trouble selecting a date with the Bootstrap datepicker class. After running the snippet, the calendar appears below the textbox: <input type="text" class="form-control datepicker" name="due_date" id="due_date" onclick="calendar_up()" value="" pl ...

What causes the "node: bad option" error to occur when I include a custom flag in the nodejs command line within an Angular 9 application?

Seeking assistance with adding a custom flag to the npm start command in an Angular 9 project. The goal is to intercept proxy requests within the local server and manipulate data. However, encountering the "node: bad option" error consistently. Looking for ...

Encountering a handshake error when connecting Node.js and MySQL modules

After working with Codeigniter for years, I found myself needing to use MySQL in Node.js. However, connecting the libraries has been a messy and tricky process, with connection issues being my main problem. I'm currently developing an adapter to hand ...

Offline Capabilities in Angular Application

I'm looking to enhance the offline functionality of my Angular application. I initially considered using App Cache, but it's now deprecated and Service Workers are still experimental. Any recommendations on what alternative technology I should us ...

Failure to fetch data through Axios Post method with a Parameter Object

I've encountered an issue with Axios while attempting to make a post request with a parameters object to a Laravel route. If I use query parameters like ?username=user, the post request works successfully. However, when I use an object, it fails: Be ...

Whenever I enter a narrative into my text box, it must interact with this API

Whenever I enter a story in the text box, it should trigger this API call: The retrieved data should be displayed in the browser. Currently, the API call is not being made. All the relevant code can be found in 'searchbar.js'. Could you please ...