AngularJS is incapable of detaching forms from objects

Creating forms dynamically using ng-repeat and adding them to the vm.forms object is causing issues. When an item is removed from the array, the corresponding form is deleted but the key in the vm.forms object remains, leading to undefined errors.

angular
    .module('myApp', [])
    .controller('FormLooper', FormLooper);

function FormLooper() {
    var vm = this;
    
    vm.children = [{
        name: 'Sarah',
        age: 9,
    }, {
        name: 'John',
        age: 13,
    }];
    vm.removeChild = removeChild;
    vm.forms = {};
    vm.showSummary = false;
    vm.triggerError = triggerError;

    function triggerError() {
        console.log('Available forms:', vm.forms);
        console.log('property names:', Object.getOwnPropertyNames(vm.forms));

        Object.getOwnPropertyNames(vm.forms).map(function(key) {
            console.log('key', key, vm.forms[key]);
            return vm.forms[key].$valid; // This will result in an `undefined` error
        });
    }

    function removeChild(index) {
        vm.children.splice(index, 1);
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<body ng-app="myApp">
    <div ng-controller="FormLooper as vm">
        <div ng-repeat="child in vm.children">
            <form name="vm.forms.formId{{ $index }}">
                <label>
                    Name: <input ng-model="child.name">
                </label>
                <br>
                <label>
                    Age: <input type="number" ng-model="child.age">
                </label>
            </form>
            <button ng-click="vm.removeChild($index)">RemoveChild</button>
        </div>
        <button ng-click="vm.triggerError()">Trigger Error (check your console output)</button>
    </div>
</body>

View the code on JSFiddle for reference: http://jsfiddle.net/Tobbe/8eohL2nq/2/

It seems that Angular doesn't delete the entire object property automatically. One solution could be manually using delete in the removeChild function, but it's not ideal. Another option is to check for undefined in the map function, which feels like a workaround. Is there a better way to handle this?

Any insights on how Angular handles adding and removing objects from vm.forms would be appreciated.

UPDATE:

Note that even though Angular populates the vm.forms object when forms are created, it doesn't remove entries when forms are deleted. Is this behavior intentional or a bug?

Answer №1

When working with apples and peaches...

Instead of using vm.forms.formid{{$index}} to search for a vm.forms object that was never initialized.

You have two possibilities: 1. Utilize the children array:

<div ng-repeat="child in vm.children">
            <form name="vm_forms_formId{{ $index }}">
                <label>
                    Name: <input ng-model="child.name">
                </label>
                <br>
                <label>
                    Age: <input type="number" ng-model="child.age">
                </label>
            </form>
</div>

This method will provide you with valid form names (you could also utilize IDs of the children).

  1. Utilize both the forms array and children array, but make sure to initialize the forms object first...

Answer №2

The desired functionality should ideally be taken care of by the AngularJS parser, however it is currently not supported. The simplest solution for now is to simply verify for undefined when accessing.

For further information, visit: https://github.com/angular/angular.js/issues/14510

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

Managing nested levels in Vue Draggable

Here is a link to the code sandbox: Nested Draggable Code Sandbox The nesting in this code is controlled through directives, specifically using v-if: <template> <draggable class="dragArea" tag="ul" :list="tasks" :g ...

Is there something incorrect with the incrementation in JavaScript?

for (let i = 0; i < 5; ++i){ alert(i); } for (let i = 0; i < 5; i++){ alert(i); } Both of these constructs get the same result: 0, 1, 2, 3, 4. But what are the underlying differences between them? And does the choice of increment in a for l ...

Adjusting the filter location in React-admin

This is the common method of implementing filters in react-admin https://i.stack.imgur.com/M8yq7.png However, in my particular scenario, I require the filters to be inside each column heading. For example: https://i.stack.imgur.com/GU2Pz.png The filter ...

Merging Documents in PouchDB

I need to retrieve equipment data from pouchdb/couchbase that has users assigned to them. Each piece of equipment has an _id and a checkedOutBy field with the user._id as its value. The employee object contains the user's name. How can I retrieve the ...

Change in ReactJS URLs without causing the entire page to refresh when using BrowserRouter

After conducting extensive research and struggling for a solution for quite some time, it appears that I am facing an issue with my ReactJS project. As a beginner in ReactJS, I have developed a game (a quiz) with multiple levels where the component remains ...

Calculating the total sum in Vuejs when an event is triggered

I am faced with a situation where the price of a product is added to an existing total when a user increases the quantity. However, the problem lies in the fact that even if the user decreases the quantity, the price continues to increase. Solution html ...

Ways to verify if a value is a numeric value

Here is a function that I am working with: $scope.SearchTicketEvent = function (ticketPinOrEvent) { if (ticketPinOrEvent != undefined) { if (ticketPinOrEvent.length == 10) ...

Is there a risk of overloading the server and browser by making constant AJAX calls at regular intervals?

I am in the process of creating a website that requires notifications. I want to use AJAX to continuously check for updates in my database where notifications are stored at regular intervals. My concern is, with multiple users all accessing the AJAX call ...

The function of AJAX is to send and receive data asynchronously without

Recently, I was experimenting with AJAX. When I use echo "hello" in my PHP file, everything works perfectly. However, if I try something like echo "<script language=Javascript> alert('hi');</script>"; in the PHP file, the alert ...

Is it possible to bind to a service variable in a controller without using $scope and utilizing the

As I delve into the world of controllerAs syntax in AngularJS, I've encountered a snag when attempting to bind a service variable. The traditional approach using `$scope.$watch` or `$scope.$on` would require injecting `$scope`, which seems counterintu ...

The issue with Array.prototype.join in Internet Explorer 8

In my current working scenario, I encountered an issue with the following code snippet. It performs well in the latest versions of Internet Explorer (IE), but the join function fails to work correctly in IE 8 Version. <!DOCTYPE html> <html xmlns= ...

Spinning load button using Angular's ng-repeat feature

I utilized ng-repeat to exhibit some information from an array. However, the data size was overwhelming, so I implemented a limit with ng-repeat and included a "load more" button to fetch additional items from the array. Now, I am interested in incorporati ...

Tips for Dynamic Importing and Rendering of Components in ReactJS

I'm looking to dynamically import and render a component in React. I have two components - Dashboard and Home. Essentially, I want to dynamically render the Dashboard Component inside the Home Component without having to import it beforehand or maybe ...

Renaming and destructuring of an array's length using ReactJS

I am working with a reduce function shown below: let el = scopes.reduce ((tot, {actions}) => tot + actions.length, 0); I attempted to modify it as follows, but it appears that this is not the correct approach: let el = scopes.reduce ((tot, {actions.l ...

Having trouble getting JQuery Ajax POST to work in Codeigniter

Encountering an issue with jQuery AJAX post in CodeIgniter, where clicking the submit button triggers an error. Below is the code snippet: home.js form.on('submit', function(e){ e.preventDefault(); var fields = {}; form.find(' ...

What is the process for saving selected values from a drop-down list into a database?

Hey there, I'm a newcomer to PHP and ajax. When choosing an option from the drop-down list, a separate div function should appear where I need to insert both the selected option and input data in different divs. Sorry for my poor English. Any help fro ...

Having trouble populating Extjs Grid with JSON data

In this simple grid, I am attempting to display three columns - Subject ID, Subject Name, and Subject Short Name by obtaining JSON data. The data is stored in a variable called myData in JSON format, which has been received from the server. Despite pasting ...

Is there a method to prevent the repetition of this loop?

I have a question regarding my React app development. I am currently using useEffect to loop through six items every time, even when only one item has changed. How can I optimize this so that only the variable that was changed in the reducer function is ...

Is there any more Angular code to be bound using ng-bind-html or ng-bind?

Hey there! Just a quick Angular inquiry: <div class="_minimal_size margin_10_middle"> <div class="_50 espaciado_0_20"> <p ng-bind-html="eirana_knows.feedback"></p> </div> <br class="clear"/> </div ...

What is the best way to extract all of the JSON data from Firebase using a web platform?

As a newcomer to Firebase and noSQL databases, I'm encountering difficulties in extracting all the JSON data from the database. Although I've gone through the firecast tutorials and understand how to retrieve specific values by referencing the da ...