Enabling ng-disabled within an ng-repeat loop

I'm facing an issue with a form that is nested inside an ng-repeat directive. The form should only be enabled if a specific field (in this case a select dropdown) is selected, but for some reason, it's not working as expected. Can anyone provide a solution to fix this problem?

<form name="myForm">    
        <div ng-repeat="item in data">
            <select ng-model="name" required ng-options="r.id as r.name for r in list">
                <option value="">--Select---</option>
            </select>    
            <button class="button" ng-click="save()" ng-disabled="myForm.$invalid">Save</button>
        </div>    
    </form>

Answer №1

Utilize the ng-form directive, a detailed guide can be found here

<form name="myForm" novalidate>  
    <div ng-repeat="item in data">

        <ng-form name="testForm">
            <select ng-model="name" required ng-options="r.id as r.name for r in list">
            <option value="">--Select---</option>
            </select>    
            <button class="button" ng-click="save()" ng-disabled="testForm.$invalid">Save</button>
         </ng-form>

    </div>    
</form>

Check out this demo on Plunker

For further clarification, refer to this article

Answer №2

Since your form is nested inside ng-repeat, you will end up with multiple forms bound to $scope all named myForm (which will be overwritten).

To solve this, give each form a unique name within the ng-repeat.

For example:

<form name="myForm{{$index}}">

Then, on your button:

<button class="btn-submit" ng-click="submit()" ng-disabled="myForm{{$index}}.$invalid">Submit</button>

Answer №3

To make your code more organized, consider assigning a name to each select element. This way, you can easily identify and handle field errors individually:

<form name="myForm">
    <div ng-repeat="item in data">
        <select ng-model="name" name="name{{$index}}" required ng-options="r.id as r.name for r in list">
            <option value="">--Select---</option>
        </select>
        <button class="button" ng-click="save()" ng-disabled="myForm['name' + $index].$invalid">Save</button>
    </div>
</form>

Check out the live example here: http://plnkr.co/edit/RVY39iMv3dy96Cuw4q6B?p=info

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

Show data based on the chosen destination

Recently, I've been working on creating a simple printer manager to monitor the status of all my printers. Although I have successfully displayed all the data, I'm facing an issue while trying to organize it by location. The error message I keep ...

The two divs are positioned on top of one another, with the link in the bottom div being unclickable

I am trying to create a unique effect where a tile divides into two on hover, with each tile acting as an individual link. Additionally, I want the background color of the tiles to change on hover. To achieve this, I have stacked two divs (toptile and bot ...

Best practices for utilizing the getTile() method within Google Maps

I have a question about storing markers in a database using tile IDs. The goal is to display all the markers associated with a specific tile when it is displayed on a map. Initially, I created a code that was not working correctly. It only requested one ...

"Using the check function in JavaScript to determine if a value

I have a JSON file containing data, and I am looking to create a function that extracts only the values from each object and adds them to a list. Is there a more efficient way to write this code so it can run indefinitely and continue pushing non-object v ...

Using Jquery to dynamically add an active class to a link if it matches the current URL

Is there a way to modify the code below so that only the exact current URL will have the active class added? Currently, even when the URL is http://localhost/traineval/training, it also adds the active class to http://localhost/traineval/training/all_train ...

Utilizing object UUID keys to associate products in VueJS

Hey there, I've gone ahead and created an object with UUIDs but now I'm looking for a way to link these UUIDs to specific items. It seems like there needs to be some separation between the UUID and the rest of the object, however, my main issue i ...

Issue with Angular 2 (Ionic 2): Struggling to properly display Component within Page

I have successfully created an Angular 2 Component: import {Component, View} from 'angular2/core'; @Component({ selector: 'sidemenu' }) @View({ templateUrl: 'build/pages/menu/menu.html', }) export class Menu { } Howev ...

Personalized parallax design

I am in the process of developing my own custom parallax plugin to allow me to control the direction in which items transition off the screen. However, I am currently facing a challenge in ensuring that regardless of how a user scrolls or the size of the w ...

What is the best way to choose the right value based on parameters?

I am currently working on a solution using protractor where I have several options to consider. Specifically, I need to test timeslots between 1600 and 1900, along with an else statement. For instance, if the 1600 timeslot is selected, then the code shoul ...

Async function captures error being thrown

I am looking to implement an async function in place of returning a promise. However, I've run into an issue with rejecting using error throwing: async function asyncOperation() { throw new Error("Terminate this application."); } (async () => { ...

Employing Isotope/jQuery for organizing posts on Tumblr in columns with the ability to infinitely scroll

Alright so, here we have the classic dilemma where scripts are running before images load. And to make matters more complicated, on Tumblr, there's no way to access image dimensions before they're loaded into the DOM... $('#thumbnails&apos ...

Am I on the right track with my service definition in Angular?

(function(){ angular.module('myApp',[]) })(); (function(){ angular.module('myApp.dashboard',[]) })(); (function(){ angular.module('myApp.value',[]) })(); (function(){ 'use strict'; angular.modu ...

Guide to removing a particular textfield from a table by clicking a button with ReactJS and Material UI

I need assistance with deleting a textfield on a specific row within a table when the delete button for that row is clicked. Currently, I am able to add a text field by clicking an add button and delete it by clicking a remove button. However, the issue is ...

Retrieving string-based JSON information

Within my text box, the user inputs strings separated by commas. These strings are split on the front end, then sent to the backend to retrieve data in JSON format. The interesting part is that when I directly entered the key of the JSON, like this, it wo ...

How does the 'Route' parameter serve in the Restangular methods oneUrl() and allUrl()?

Check out the signature for the oneUrl function: oneUrl(route, url). Here's what the documentation says: oneUrl(route, url): Using this will generate a new Restangular object that points directly to a single element with the specified URL. I fin ...

Retrieving a specific Project ID from Asana Task API using Node.js and parsing the JSON response

Utilizing the Asana Task API, we have the capability to retrieve a task's associated projects along with their GID and Notes (description text). The main objective Our aim is to extract the GID of the project containing #websiteprojecttemplate in its ...

What is preventing me from making a call to localhost:5000 from localhost:3000 using axios in React?

I have a React application running on localhost:3000. Within this app, I am making a GET request using axios to http://localhost:5000/fblogin. const Login = () => { const options = { method: "GET", url: "http://localhost:5000/fblogin", ...

JavaScript for validating forms in PHP

Hey everyone, I'm struggling to understand why the alert box isn't showing up when I run this code. I'm new to programming and find HTML easy, but I'm currently in a PHP class where we have been tasked with creating and validating a for ...

What could be causing the bootstrap 4 col-md-3 block to shrink when using position fixed?

When working with Bootstrap 4, I encountered an issue where changing the block position from relative to fixed using a script caused the block to decrease in size. The script I used includes a .sticky class: .sticky { position: fixed !important; top: ...

Troubleshooting Cross-Origin Resource Sharing problem with Stripe API integration in Angular

I am diving into the world of Stripe API and CORS for the first time. I've set up a POST request from Angular to my Node.js server. Since the client origin differs from the server destination, I have implemented CORS on the server side. When inspectin ...