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-loginangular.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
})
});