How can we determine the total number of mandatory fields in an AngularJS form?

Can you explain how to calculate the number of required fields in a form using AngularJS? In my form, there are two required fields (email and select view). I want to display the count on my page - showing 2 if email is filled, 1 if only email is filled, and 0 if both email and select view are filled.

I attempted to create a directive and broadcast the count value to the controller, but it is not providing the correct value. Here is the code snippet:

http://codepen.io/anon/pen/WGzgdE?editors=1010#anon-login
angular.module('app',[]).directive('requiredCount',function($rootScope){
        return {
            restrict: 'EA',
            require: '^form',
            link: {
                post: function (scope, elem, attr, ctrls) {// jshint ignore:line
                    console.log('ctrls.$name', ctrls.$name);
                    scope.$watch(function () {
                        if (ctrls.$error.required) {
                            return ctrls.$error.required;
                        }

                    }, function (newValue, oldValue) {
                        if (newValue && newValue !== oldValue) {
                            var count = newValue.length;
                            newValue.forEach(function (item) {
                                if (item.$error.required) {
                                   // if (item.$valid) {
                                        count--;
                                  //  }
                                }
                            });

                        }
                    });
                }
            }
        };
    }).controller('app',function($scope){
  $scope.$on('count',function(e,a){
    $scope.count =a
  })
});

Answer №1

Make sure to include the name attribute in your form elements and add the 'ng-model' attribute to each element.

<form name='test' novalidate> 
 <div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" ng-model="user.email"  id="email" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
 <input id="pwd" name="pwd" class="form-control"   
  type="password" ng-model="user.password" required></input>
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<select name="carlist" class="form-control" ng-model="user.carlist" id="carlist" required>
 <option value></option>
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="opel">Opel</option>
 <option value="audi">Audi</option>
</select> 
<button type="submit" class="btn btn-default">Submit</button>
</form>

You can use "test.$error.required.length" to show how many required fields are missing.

required field count {{test.$error.required.length}}

Check out the DEMO here - http://codepen.io/anon/pen/jrzZLX?editors=1010#anon-login

Answer №2

try implementing form.$error.required.length

<div ng-show="form.$invalid">
       Unfortunately, there are {{form.$error.required.length}} errors occurring.
</div>

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 receiving user input with custom values and assigning them to variables through multiple selection criteria using Jquery

I am encountering an issue with a form that contains multiple selection blocks. I am attempting to extract the values of each block criteria on click in order to send it to a database. However, every time I click on a block, my script retrieves all the val ...

The Kendo Grid is not displaying any data when trying to bind the data source using an ajax callback to the controller

My query is quite similar in nature to this: Binding Kendo Data Source with Async $.ajax calling from C# MVC Controller Action Below is the javascript code used for generating the Kendo grid: $(document).ready(function () { $("#grid").kendo ...

Tips on resetting the position of a div after filtering out N other divs

Check out this code snippet. HTML Code: X.html <input type="text" id="search-criteria"/> <input type="button" id="search" value="search"/> <div class="col-sm-3"> <div class="misc"> <div class="box box-info"> ...

Common mistakes made while working with decorators in Visual Studio Code

Having trouble compiling TypeScript to JavaScript when using decorators. A persistent error message I encounter is: app.ts:11:7 - error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the ' ...

Guide to ensuring every request in an Express.js application contains a cookie

Currently, I am in the process of developing a CRUD application using both React and Node. As part of my development, it is crucial for me to validate whether the cookie is present or not for each request. app.all("*", (req,res) => { // If the cookie ...

Issue with JQuery's click and submit events not triggering, but change event is working fine

My webpage has a dynamic DOM that includes add and save buttons to interact with elements. Each row also has a remove option for deletion. When a user logs in, the controller redirects them to their homepage in the codeigniter PHP framework. This controlle ...

Having trouble loading the Google API using getScript. Is displaying a ReferenceError message: "Variable google not found."

I am attempting to dynamically load the Google API using the getScript() method for implementing a "Place Autocomplete Address Form". For more information, you can visit this link: https://developers.google.com/maps/documentation/javascript/examples/places ...

Is there a way to eliminate empty arrays from my data?

I'm dealing with this PHP code snippet. public function display_children($parent,$level){ try { $cmd = $this->connection->prepare('SELECT mem,pid from mytree where pid = ?'); $cmd->execute(array($parent)); ...

Enhancing Chat: Updating Chat Messages in Real-Time with Ember.js and Firebase

I recently started working with ember.js and firebase. Right now, I have successfully implemented a feature to post messages and view them in a list format as shown below: //templates/show-messages.hbs {{page-title "ShowMessages"}} <div clas ...

What is the best way to showcase a singular item from response.data?

Below is the controller I have set up to display details of a single book from my collection of json records .controller('BookDetailsController', ['$scope','$http','$stateParams',function($scope,$http,$stateParams){ ...

Simple server using node.js and express to host an HTML file and associated resources

I am currently experimenting with frontend development and need a basic web server to quickly start projects and serve files. Specifically, I have one index.html file along with some css/js/img files. I decided to work with Node.js and Express for this pur ...

The environmental variable remains undefined even after it has been established

I've been experimenting with setting my environment variable in the package.json file so that I can access it in my server.js file. Despite trying NODE_ENV=development, set NODE_ENV=development, cross-env NODE_ENV=development, and export NODE_ENV=deve ...

Get the div to occupy the rest of the available height

I am facing a challenge with two divs on my webpage. The bottom one contains content that expands the highest. The page is set to 100% height and width using the CSS property position: absolute. <style> body, html { height:100%, width:100% } ...

In production mode, the Angular/JS Express app is stuck in an endless routing loop, while it functions perfectly in development mode

My webapp is constructed using generator-angular-fullstack. While it functions properly in development mode (grunt serve), I encounter a problem with what appears to be an endless routing loop when switching to production mode (grunt serve:dist). The outp ...

Tips on transforming a JSON file into a response for my personal server

After successfully converting an Excel file to JSON format using my code, I encountered a challenge when trying to convert this as a response. Despite attempting to use res.send in the JS code, it only displayed directory/inner codes instead of a response. ...

React is unable to locate the component element within the DOM

I'm attempting to set the innerHTML for the div element with the ID of ed. Unfortunately, I am unable to access it once React has finished rendering. It seems that this is due to the render stages, as I am receiving a null value for the div element. W ...

Preserve the Browser Scroll Position when navigating to another page

Currently tackling a challenge with JS, JQuery, and PHP where I'm attempting to resolve an infinite scroll issue. The specific problem arises when scrolling down the page extensively while loading more pages via ajax, then navigating to a different pa ...

React.js: The function useDef has not been defined

Attempting to create a React.js calculator application, my initial step was to delete the entire src folder and replace it with a new one containing the necessary elements for the web app. Here is the content of the index.js file: import React,{ useEffect, ...

assigning a variable using jQuery

<script> function update(elem) { var ele=$(elem).siblings('label#test').html(); var a=document.getElementById('test'); var htm = '<input type="text" name="modal" id="modal" style="width:70%;" value="'+$(elem).siblings ...

Issue with HighCharts: Bar columns not extending to the x-Axis when drilling up

I am encountering an issue with HighChart/HighStock that I need help with. To illustrate my problem, I have set up a JSFiddle. The problem arises when a user drills down on a bar column, causing the y-axis to shrink and consequently making the x-axis appea ...