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

The setting `ensureCleanSession: true` doesn't appear to be effective when included in the capabilities for Internet Explorer 11

Currently, I am testing a login/logout application with the help of protractor. One challenge I am facing is dealing with a popup that appears after each login/logout scenario. In order to ensure the popup appears after each login, I need to reset the IE ...

Utilizing Vue-i18n for language translations directly within a JavaScript file, rather than using

Is there a way to utilize the .js file for translations instead of the .json file? I attempted changing: const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i) to const locales = require.context('./loca ...

Tips for using Angular's formatDate function to format dates

I am attempting to achieve a specific format using Angular's formatDate "2019-01-01T00:00:00Z" Here is the code I am using: formatDate( '2019-01-01', 'yyyy-MM-ddT00:00:00Z', 'en-US' ) The output I am getting is ...

The ES6 method of binding click handlers with parameters in React

After reading numerous articles on the usage of () => {} syntax, binding in the constructor, and binding in the props, I have come to understand that binding this can be performance-intensive. Furthermore, automatic binding with arrow functions incurs a ...

Angular 4 after ejection, coupled with automated end-to-end testing using Protractor/Selenium setup

I am attempting to conduct end-to-end tests using Protractor/Selenium on an Angular 4 project that has been ejected. Here is my package.json: ... "scripts": { "pree2e": "webdriver-manager update --standalone false --gecko false --quiet node", "e2 ...

Steps to create a toggle feature for the FAQ accordion

I am currently working on creating an interactive FAQ accordion with specific features in mind: 1- Only one question and answer visible at a time (I have achieved this) 2- When toggling the open question, it should close automatically (having trouble with ...

Having trouble with bootstrap carousel malfunctioning on Firefox browser?

I'm experiencing an issue with the carousel slider on my website. It seems to only be working in Chrome and not in Mozilla Firefox. You can view the live site at: Below is the code I have used for the carousel: <header id="myCarousel" class="car ...

Storing Images in MongoDB with the MEAN Stack: A Guide using Node.js, Express.js, and Angular 6

I am currently working on developing a MEAN Shop Application, and I have encountered an error while attempting to store the product image in MongoDB. typeError: cannot read the property 'productimage' of undefined Below is the route function fo ...

Setting a value in Ionic 3 HTML template

Attempting to assign a value in an Ionic 3 template from the ts file while also adding css properties but encountered an issue. PROBLEM Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No va ...

Removing cookies after sending a beacon during the window unload event in Chrome

Here's the situation: I need to make sure that when the browser is closed or the tab is closed, the following steps are taken: Send a reliable post request to my server every time. After sending the request, delete the cookies using my synchronous fu ...

Maximizing the potential of $urlRouterProvider.otherwise in angular js

I am encountering an issue with redirecting to the login screen when there is no UABGlobalAdminId in my storage. I have tried using $urlRouterProvider.otherwise but it doesn't seem to be functioning properly. When I attempt to debug, the console does ...

Is it possible to combine TypeScript modules into a single JavaScript file?

Hey there, I'm feeling completely lost with this. I've just started diving into Typescript with Grunt JS and I could really use some assistance. I already have a Grunt file set up that runs my TS files through an uglify process for preparing the ...

Maintaining the proportions of images in different screen sizes when resizing

I apologize if this question has already been addressed, but I have been unable to find a solution that works for my specific issue. My Gallery consists of a side list of available images in one section, which when clicked changes the image source in anot ...

Is it really necessary to still think poorly of JavaScript in 2011?

Here's an intriguing question for you. I've tested out a variety of popular websites, including Facebook, and I've noticed that many features still work perfectly fine even when JavaScript is disabled. People always used to say that JavaScr ...

Is there a way to display errors during jQuery validation?

Is there a specific function that can provide all error messages generated during form validation? I attempted to use the defaultshowerrors() function, but it only shows errors for the current element being validated. Is there a way to retrieve all error ...

What are some ways I can customize the appearance of this Google Maps infoWindow?

I was able to create a Google Maps script using JavaScript code. The map displays multiple locations with corresponding latitude and longitude coordinates. This script can be viewed at . My objective now is to customize the appearance of the info windows ...

Scope variable changes are not being acknowledged by the directive

Here is a directive I am working with: <span ng-show="{{ save_state == 'saved' }}"> Saved </span> <span ng-show="{{ save_state == 'saving' }}"> Saving </span> <span ng-show="{{ save_state == 'error ...

Error: export keyword used incorrectly

Currently, I am in the process of developing an npm package called foobar locally. This allows me to make real-time changes and modifications without the need to constantly publish and unpublish the package, which greatly improves my development efficiency ...

Display items from two different collections next to each other by utilizing two ng-repeat directives

I have 2 collections: one for names and one for values. How can I display them using bootstrap columns and angularjs, similar to the image provided in the link below? View the image for reference My attempted code is shown below, however, it does not giv ...

What are some techniques for reducing the number of pages in my Carousel?

I need help figuring out how to set a limit of noOfPages for the number of pages per carousel. The functions in my code below don't implement this and I'm unsure how to do it. const itemsPerPage = 6; const [page, setPage] = React.useState(1); ...