Steer clear of replicating angular elements in the ng-model aspect

Whenever I click on the add button, new inputs are dynamically added.

Here is an example on JSBin for you to review my problem.

Each time I press the mentioned button, a new input should appear. Currently, there are 2 forms/boxes visible in the same view generated by ng-repeat with separate inputs and an individual add more button. The issue arises when I click the button, two new inputs show up in different forms instead of just one in the current form.

    <div>
        <div ng-repeat="op in operation track by $index">
            <p>{{op.title}} | {{op.duration}} | {{op.status}}</p>
            <input ng-model="operation.detailText" type="text"></input>
            <div>
                <div ng-repeat="operation in operations track by $index">

                    <input ng-model="operation.detailText" type="text"></input>

                </div>
                <button ng-click="operations.push({})">Add one more</button>
            </div>
        </div>
    </div>

JS:

angular.module('ionicApp',[])

.controller('mainCtrl', function($scope) {

    $scope.operations = [];

    $scope.operation = [];

    $scope.operation = [{
                    title    : 'Operación 170794',
                    duration : '3600',
                    status   : '0'
                  }, {
                    title    : 'Operación 981922',
                    duration : '60',
                    status   : '0'
                  }];

});

Answer №1

It is crucial to maintain clarity in your code by distinguishing between different concepts (such as operations versus operationTypes) and avoiding blending them together. Using distinct names for variables can help prevent confusion in your code.

You can view the code example at: jsbin.com/hujerurivu/1/edit?html,css,js,output

angular.module('ionicApp',[]).controller('mainCtrl', function($scope) {
    $scope.operationTypes = [{
                    title    : 'Operación 170794',
                    duration : '3600',
                    status   : '0'
                  }, {
                    title    : 'Operación 981922',
                    duration : '60',
                    status   : '0'
                  }];

    $scope.operations = {};
    angular.forEach($scope.operationTypes, function(operationType){
        $scope.operations[operationType.title] = [];
    });
});

--

<div class="panel panel-default">
    <div class="panel-body" ng-repeat="operationType in operationTypes track by $index">
        <p>{{operationType.title}} | {{operationType.duration}} | {{operationType.status}}</p>
        <div>
            <div ng-repeat="operation in operations[operationType.title] track by $index">
                <input ng-model="operation.detailText" type="text"></input>
            </div>
            <button ng-click="operations[operationType.title].push({})">Add one more</button>
        </div>
    </div>
</div>

Answer №2

When working with JavaScript objects that point to the same array, you'll get the same output because objects are referenced and arrays are objects. To keep the lists separate, add a key named operations to each object.

To achieve this, modify your operation objects as shown below:

angular.module('ionicApp',[])

.controller('mainCtrl', function($scope) {
    $scope.operation = [{
      title    : 'Operación 170794',
      duration : '3600',
      status   : '0',
      operations: []
    }, {
      title    : 'Operación 981922',
      duration : '60',
      status   : '0',
      operations: []
    }];

});

Update your loops in the following manner:

<div class="panel-body" ng-repeat="op in operation track by $index">
                <p>{{op.title}} | {{op.duration}} | {{op.status}}</p>
                <input ng-model="operation.detailText" type="text"></input>
                <div>
                    <div ng-repeat="operation in op.operations track by $index">

                        <input ng-model="operation.detailText" type="text"></input>

                    </div>
                    <button ng-click="op.operations.push({})">Add one more</button>
                </div>
            </div>

You can also include an index for each operation pushed to the operations list and filter using ng-if:

<div class="panel-body" ng-repeat="op in operation track by $index">
    <p>{{op.title}} | {{op.duration}} | {{op.status}}</p>
    <input ng-model="operation.detailText" type="text"></input>
    <div>
        <div ng-repeat="operation in operations track by $index" ng-if="operation._index === $index">

            <input ng-model="operation.detailText" type="text"></input>

        </div>
        <button ng-click="addOperation($index)">Add one more</button>
    </div>
</div>

angular.module('ionicApp',[])

.controller('mainCtrl', function($scope) {
    $scope.operations = [];

    $scope.operation = [{
      title    : 'Operación 170794',
      duration : '3600',
      status   : '0'
    }, {
      title    : 'Operación 981922',
      duration : '60',
      status   : '0'
    }];

    $scope.addOperation = function(index){
        $scope.operations.push({
            _index: index
        });
    };
});

Answer №3

By incorporating an array into each 'operation' object, you can iterate through them individually as illustrated:

Doing this ensures that the forms and inputs remain distinct from one another.

http://example.com/example-link

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 Angular UI Router is rendered ineffective because of the issues with the factory and resource

I've been referring to a tutorial on YouTube at this link: https://www.youtube.com/watch?v=X_NZr_-RaLw. In my clientapp.js file, when I include the following code snippet: .factory('UserService', function($resource) { return $resource( ...

Dealing with CORS error when making requests to Firebase Realtime Database API within a Vue project

I am currently working with vue-2 and I need to perform a shallow query on the Firebase real-time database by fetching an API. However, when running on my development server, I encounter a CORS blocked issue. What steps should I take to resolve this? PS: I ...

The Bootstrap modal stubbornly refuses to close even after resetting the HTML body

I am having an issue with my bootstrap modal where the closeModal button is not functioning properly after the printModal button has been clicked. The modal does not close as expected. Step 1: Click on the printModal button after the modal pops up (this w ...

Angular scope object fails to be updated

I recently developed an Angular module for translation that works perfectly in two of our applications. However, when I tried implementing it in a new application, it didn't work as expected. The controller for our new application looks like this - ...

Swapping out image sources using a React Hook that includes an onClick event

Despite my best efforts, I have yet to find a solution to this problem. To keep things brief, I am attempting to implement a dark mode toggle in my React application, but my current method feels like a hack. The main issue I am facing is changing the imag ...

Stop the print dialog box from causing the page to refresh

I have implemented a print button for an invoice: </script> <!--Function for printing invoice--> <script> function printpage() { window.print() } </script> <button id="print" name="print" class="btn btn-info" onClick="pri ...

The creation of a MozillaBrowserBot object has encountered an error

Attempting to access the MozillaBrowserBot object in Mozilla JS has been unsuccessful for me. The code I utilized is shown below: function externalApplication(){ var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Com ...

Invoking a parent method in ReactJS through two layers of components using TypeScript

I'm facing an issue while trying to call a method from a parent component that is two layers above. Whenever I attempt to do so, nothing happens or I get an error saying that the function is not defined. Here is my Child Component: class Child extends ...

Learn the steps to modify or remove table information from a database using a webpage

Hey there! I'm currently working on an Ajax jQuery function that displays table data, like in the image provided. I would like to add an option for users to edit and delete the table data, with the changes reflecting in the database. It's worth n ...

Node.js project that was once functional is now encountering issues with the error message: "Error: Route.post() requires a callback function but received [object Undefined]."

When it comes to asking questions, I typically provide a lot more detail and use specific wording in my titles. However, I'm currently facing an issue that has left me stumped on where to find the solution. Recently, I delved into learning Node JS an ...

Improving the display of events with fullcalendar using ajax requests

I have integrated the fullcalendar plugin from GitHub into my project. I am looking to implement a feature where I can retrieve more events from multiple server-side URLs through Ajax requests. Currently, the initial event retrieval is functioning proper ...

How can I prevent anchors from performing any action when clicked in React?

My dilemma involves this HTML element: <a href onClick={() => fields.push()}>Add Email</a> The purpose of the href attribute is to apply Bootstrap styles for link styling (color, cursor). The issue arises when clicking on the element caus ...

Utilizing React Recharts to create personalized tooltips

In my current project, I am looking to create a custom tooltip to replace the default one in recharts. The default tooltip that I want to change is shown below: https://i.stack.imgur.com/TjTiL.png I would like the new custom tooltip to look like this: ...

Verifying Function Calls in Angular Unit Testing: Handling Cleared $scope Elements

In my controller function, I have the following code: $scope.clearMarkers = function(){ for(var i = 0; i < $scope.markers.length; i++){ $scope.markers[i].setMap(null); } $scope.markers = []; }; The unit test I wrote for this code i ...

The Node.js Express Server runs perfectly on my own machine, but encounters issues when deployed to another server

I've encountered a strange issue. My node.js server runs perfectly fine on my local machine, but when I SSH into a digital ocean server and try to run it there, I get this error. I used flightplan to transfer the files to the new machine. deploy@myse ...

Testing the scope of an Angular directive

Encountering an issue with the unit test In my code, I have: describe('test controller', function () { var =$compile, scope, rootScope; beforeEach(module('myApp')); beforeEach(inject(function (_$compile_, _$rootScope_) { ...

Error message "e.nodename undefined when set to setTimeout" was encountered

I developed a unique piece of code for input boxes located at the top of different tables. By using a class='filt', the table can be filtered based on the inputs provided. However, most of the inputs consist of more than one letter, so I wanted t ...

Tips for dynamically changing the class of a form field in jQuery when it is empty

I am currently working on a form that looks like this; <form id="myform" name="myform"> <input type="text" class="required" value="" name="qwer" /><br /> <input type="text" value="" name="asdf" /><br /> <input type=" ...

Counting numbers and displaying results using JavaScript with a JSON string

Looking at this JSON string { "ResultSet": { "version": "1.0", "Error": 0, "ErrorMessage": "No error", "Locale": "us_US", "Quality": 40, "Found": 2, "Results": [{ "quality": 72, ...

How can I display several custom markers that are constantly updating on a Google map with MySQL and PHP?

Currently, I am using the following code to generate markers on a Google map by retrieving data from a database. However, the issue I am facing is that it only generates one marker instead of all the markers stored in the database. & ...