Using ng-disabled on input elements within an ng-repeat directive

Showing different inputs based on an array looks like this

<div data-ng-repeat="n in langInput.values">
    <input type="text"
           id="auction_name_{{n.selected}}"
           class="form-control"
           name="auction_name_{{$index}}"
           data-ng-model="inputs.auction_name[$index + 1]"
           data-ng-minlength="5"
           data-ng-maxlength="60"
           required />
    <span data-ng-show="sellItem['auction_name_'+$index].$error.required">Required!</span>

This setup also enables AngularJS validation. After the <form> tag is closed, I want to add a "next" button. However, I need to validate the inputs before allowing the user to click the button.

The array that I'm using for ng-repeat is:

$scope.langInput = {
    count: 3,
    values: [
        {
            id: "1",
            selected: "pl"
        },
        {
            id: "2",
            selected: "eng"
        }
    ],
    add: function () {
        if (this.count < 7) {
            this.values.push({id: this.count, selected: "eng"});
            this.count += 1;
            console.log(this.values);
        }
    },
    remove: function () {
        if (this.count > 2) {
            this.values.pop();
            this.count -= 1;
            console.log(this.count);
        }
    }
};

I understand that I can use the ng-disabled directive but I'm unsure how to check these dynamically generated inputs within the loop since their names change based on the $index.

In a real project, disabling the button when any input is invalid using ng-disabled="sellItem.$error" won't work as unseen inputs may remain invalid after form completion.

I have multiple buttons at different steps with unique ng-disabled conditions to prevent advancing without completing each step's inputs.

Instead of using ng-disabled="sellItem.$error", I need to specify all relevant inputs for each step in ng-disabled logic (usually around 5 inputs per step).

For example:

ng-disabled="sellItem.first_input.$error && 
sellItem.second_input.$error && ..."

The challenge arises when trying to loop through inputs dynamically generated by JavaScript within ng-disabled:

name="auction_name_{{n.id}}"

The input names are dynamic as users can add or delete them, complicating hardcoding in ng-disabled.

Answer №1

Managing dynamically changing input names within a loop can be challenging.

A common approach is to associate each input with a property of the object in the array, ensuring it remains linked as the array changes.

Utilizing the id property of the object can also help:

<form name="sellItem" ng-submit="submit()">
    <div data-ng-repeat="n in langInput.values">
        <input type="text"
             id="auction_name_{{n.selected}}"
             class="form-control"
             name="auction_name_{{n.id}}"
             data-ng-model="n.input"
             data-ng-minlength="5"
             data-ng-maxlength="60"
             required />
        <span data-ng-show="sellItem['auction_name_'+n.id].$error.required">Required!</span>
        <span data-ng-show="sellItem['auction_name_'+n.id].$error.minlength">Too short!</span>
        <span data-ng-show="sellItem['auction_name_'+n.id].$error.maxlength">Too long!</span>
    </div>
    <button type="submit" ng-disabled="sellItem.$error">
          {{Submit}}
    </button>
</form>

Ensure unique values for the id property are generated.


Update

Added Submit button.

For additional information, refer to:

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

Tips for displaying previous values when discarding changes to a record in a material-ui table

How can I prevent changes from reflecting in a material-ui table when clicking on the X icon while editing a row? Is there a way to only save the edited record on the check (_) icon instead? Any suggestions or solutions would be greatly appreciated as I am ...

Sending a div class as a parameter to a JavaScript function

Wondering if it's possible to pass a div's class into a JavaScript function. I'm using SquareSpace so adding an id to the div is not an option, but it works fine with divs that have ids. JQuery is already loaded. This is my current train of ...

Initiating a conversation using a greeting in the Javascript bot framework

I am looking to initiate a multi-level, multiple choice dialog from the welcome message in the Bot Framework SDK using JavaScript. I have a main dialog (finalAnswerDialog) that utilizes LUIS for predicting intents, and a multi-level, multiple choice menu d ...

The disappearance of the overlay background due to modal reload in NextJS dynamic routing

I am working on a simple NextJS app where clicking on a page opens a modal with updated URL but without triggering a new navigation. The content inside the modal is displayed, while the actual page location is reflected in the URL and refresh takes the use ...

Ways to fix vulnerabilities found in an NPM audit

Upon conducting an NPM audit, I found 5 critical issues. To address 4 of them, I attempted to update @storybook/addon-essentials & @storybook/react, as they were marked as "patched in >=x.x.x", indicating that the latest versions should have resolved t ...

Bootbox Dialog Form

Looking to implement a functionality where a Bootbox dialog pops up with an "OK" button. Upon clicking the "OK" button, it should initiate a POST request, sending back the ID of the message to acknowledge that the user has read it. The Bootbox dialog fun ...

The JQuery functionality is failing to execute properly on Internet Explorer

I have developed a JQuery script that appears to be working perfectly in all browsers, except for IE 8. Interestingly, when I checked Internet Explorer's error details, it did not provide any specific information about the issue. Instead, IE simply po ...

No data is being returned by the Jquery Ajax function

I am experiencing an issue with a Jquery Ajax call in my code: $('body').on('click', '#btnPopulate', function() { alert(getTree()); }); function getTree() { var url = getUrlPath() + "/StoryboardAdmin/BuildStoryboardViewMode ...

Ways to extend the timeout duration for Vercel Serverless functions

I've encountered an issue with my API endpoint on a NextJS project where it exceeds the 60-second time limit to execute. Despite being on a pro Vercel plan, I have been unable to extend the timeout limit successfully. Within the endpoint itself, I at ...

The error callback for Ajax is triggered even though the JSON response is valid

Within my JavaScript file, I am making the following call: $.ajax({ type: "POST", dataType: "application/json", url: "php/parseFunctions.php", data: {data:queryObj}, success: function(response) { ...

Tips for validating forms using jQuery

Upon form submission, an alert is displayed before redirecting to a new page. I have implemented a function that triggers on button click. The alert will appear first, followed by the form submission. I would appreciate ideas on how to validate the form. ...

Setting up Highcharts version 7 heatmaps with npm in an Angular 6 environment

I am currently having an issue with initializing the heatmap lib in Highcharts 7.0.1 within my Angular 6 app via npm. Despite successfully running basic charts like line, spline, bar, etc., when following the documentation for the heatmap initialization, I ...

The Material UI button feature neglects to account for custom CSS styles when attempting to override the default settings

Utilizing a custom bootstrap css styles in my react app, I am seeking to enhance the default material ui components with the bootstrap styles. import React, {useState} from 'react'; import 'cg-bootstrap/core/build/cg-bootstrap-standard.css&a ...

Mongoose Does Not Allow for Duplicate Data Submissions

I'm currently working on a project to develop a basic blog application. Everything works smoothly when submitting content to the database for the first time, but if you try to submit again, Node crashes unexpectedly. I've been struggling to pinpo ...

Having trouble removing a row from Mysql database using Node.js

Recently, I developed a pet shop web application using nodeJS and MySql. Everything was working smoothly until I encountered an issue with deleting pets by their pet_id. Upon attempting to delete using pet_id 'pa04', I received the following erro ...

I am unable to halt the relentless stream of asynchronous events

Struggling to retrieve an array using a loop in the asynchronous environment of nodejs. Check out my code below: getDevices(userIDs, function(result) { if (result) { sendNotification(messageUser, messageText, result); res.send("Success"); } else { ...

Using AJAX, JQuery, and PHP to convert a given name to match the columns in a query, utilizing the data sent

One thing that I'm wondering about is how PHP handles my ajax requests. For example, consider the following code snippet: $("#addUser").on('click', '.btnAddSubmitFormModal', function() { $.post("add.php", { ...

Using Phoenix Channels and Sockets in an Angular 2 application: A comprehensive guide

My backend is built with Elixir / Phoenix and my frontend is built with Angular 2 (Typescript, Brunch.io for building, ES6). I'm eager to start using Phoenix Channels but I'm struggling to integrate the Phoenix Javascript Client into my frontend. ...

Adding elements to a nested array in AngularJS can be achieved by directly accessing the nested

This code represents the nested array structure: $scope.History = [ { isCustomer:false, userText:"some text", options:[] } Here is the array with data: //The DisplayLabel will be consistent ...

Pressing JavaScript buttons to trigger another button

I am looking to develop a script that generates a button which then creates another button. The subsequent button will be assigned an id attribute by incrementing from 1 to infinity. This feature should apply to all buttons (original button and the newly ...