count number of required field in form in angular js? - javascript

could you please tell me how to count the number of required field in form in angular js ?
In my form there is two required field is present (email, select view).So I want to show 2 in my page .when I fill email .it should show only 1 .But when I select value from select view it should show 0 value.
so I make a directive and try to broadcast count value to controller but it is not giving correct value
here is my code
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
})
});

You are missing the name attribute in the form elements and the 'ng-model' attribute on 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>
"test.$error.required.length" would simply display the no of required fields .
required field count {{test.$error.required.length}}
Here is the DEMO - http://codepen.io/anon/pen/jrzZLX?editors=1010#anon-login

you can use form.$error.required.length
<div ng-show="form.$invalid">
Sorry but {{form.$error.required.length}} errors found.
</div>

Related

How to compare values in Angularjs?

I'm a newbie to angular, so I need a help.
In html, I wrote the following
<div class="form-group">
<input type="email" name="Email" id="LoginEmail class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
In angular, I write the following code
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [
{name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"}
];
}]);
I need to compare the value of input box with the value of the script and show a message if it's not correct, so how can I do that?
Firstly you need to assign model to your template scope. Use ng-model for this purpose. Then you need a form to submit and trigger a function to check if user input matches to the desired values.
Add ng-model and wrap your inputs with a form tag:
<form ng-submit="login()">
<div class="form-group">
<input ng-model="email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
<button type="submit">Login</button>
</form>
Check if user input is valid in Controller:
$scope.login = function() {
const isUserValid = $scope.email === $scope.userinfo[0].account && $scope.password === $scope.userinfo[0].password;
if(isUserValid) {
alert("Logged In Successfully");
}else {
alert("Email or password incorrect. Try again.")
}
}
Here's a working example of the above code.
In your input elements you miss the ng-model attribute. It is used to bind the values with your scope variables.
<input type="email" ... ng-model="email" ...>
<input type="password" ... ng-model="password" ...>
And in your controller you can write
if($scope.email == $scope.userinfo[0].account && $scope.password == $scope.userinfo[0].password){
//Login ok
}else{
//Login failed
}
Assuming there is a form element somewhere above
Add ng-submit to it
<form ng-submit="submit()">
Add ng-model to the form elements.
I have added state.email and state.password
<div class="form-group">
<input ng-model="state.email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="state.password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
Compare the binding values to the values in $scope.userinfo
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [{
name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"
}];
// when you submit the form, this function will be called
$scope.submit = function (e) {
e.preventDefault();
if ($scope.state.email !== $scope.userinfo[0].account || $scope.state.password !== $scope.userinfo[0].password) {
// did not match
} else {
// matched
}
}
}]);

Angular auto form submit on validate with $watch

So I am trying to auto submit the form once it has been validated.
HTML
<form name="myForm" role="form" novalidate>
<div class="form-group">
<select class="form-control" name="location" ng-model='calc.location1' required>
<option value=7>Location1</option>
<option value=9>Location2</option>
<option value=5>Location3</option>
</select>
</div>
<div class="form-group">
<input class="form-control" type='number' name="Size" ng-model='calc.Size' placeholder="Sq ft" required>
</div>
<div class="form-group">
<input class="form-control" type='number' name="units" ng-model='calc.units' placeholder="Units in kWH" required>
</div>
</form>
Controller
myapp.controller('demoController', ['$scope', function($scope, $document) {
$scope.$watch('myForm.units.$valid', function (newValue, oldvalue){
if(newValue) {
console.log(newValue);
}
})
}])
I want to insert my form submit code inside the if statement, but newValue is always showing true even when the form inputs are empty at page load.
Trying to do something like this http://jsfiddle.net/cmyworld/EdCEW/ but no idea where I am going wrong.
The Solution is to create one method to validate all fields and set scope variable to true if all fields are valid.
var app = angular.module('myApp', []);
app.controller('myController',['$scope',function($scope) {
$scope.checked = 0;
$scope.$watch('myForm.$valid', function (newValue, oldvalue){
$scope.checkDirty();
if($scope.checked === 1)
{ alert('Model is valid');
//Can do a ajax model submit.
}
});
$scope.checkDirty = function(){
if($scope.myForm.Size.$valid && $scope.myForm.units.$valid)
{
$scope.checked = 1;
}
else
{
$scope.checked =0;
}
};
}]);
Here is the example http://jsfiddle.net/EdCEW/92/

Generate dynamic form input fields and collect field data in an array in angularJS

I need to generate form input fields dynamically by clicking 'add sale' button on the form. which is accomplished
Also on change selected drop down, it get the price from the database and use the quantity to calculate the amount of that product.
if I click on 'add sale' button for another form generate the changes affect the previous one.
how to calculate the amount for each form independently and collect the data in it using angularJS?
this is controller
appcat.controller("MainCtrl", ['$scope', '$http', '$location', function ($scope, $http, $location)
{
//var quan = $scope.quantity;
$http.get('/api/pproduct').success(function (data)
{
$scope.pcategoryA = data;
});
// this controll the addition and removal
$scope.choices = [{ id: 'choice1' }];
//any time changes occurr it calculate the Amount
$scope.changedValue = function (item,quan)
{
if (item != null && quan !=null)
{
$http.get('/api/product/'+ item).success(function (data) // this is the price for that product from the Database
{
//this sets amount field
$scope.amount = parseFloat(data.price * quan);
});
}
}
// this generate a form
$scope.addNewChoice = function ()
{
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({ 'id': 'choice' + newItemNo });
};
// this remove the form
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
if ($scope.choices.length > 1) {
$scope.choices.splice(lastItem);
}
};
}]);
this is the html
<form class="form-inline" role="form" padding-left:10em">
<strong class="error">{{ error }}</strong>
<div class="form-group">
<label for="name">
Invoice No. :
</label>
<input type="text" class="form-control" id="name" ng-model="name" />
</div>
<br /><hr />
<div ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<div class="form-group">
<label for="name">
Quantity :
</label>
<input type="text" class="form-control" id="quantity" ng-model="quantity" />
</div>
<div class="form-group">
<div class="form-group">
<label class="control-label"> Product : </label>
<select class="form-control" id="selected_id" ng-model="selected_id" ng-options="c.Value as c.Text for c in pcategoryA"
ng-change="changedValue(selected_id,quantity)">
<option value="">-- Select Category --</option>
</select>
</div>
</div>
<div class="form-group">
<label for="name">
Amount :
</label>
<input type="text" class="form-control" id="amount" ng-model="amount" ng-readonly="true" />
</div>
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
<br />
<hr />
</fieldset>
<button type="submit" class="col-sm-offset-10 addfields" ng-click="addNewChoice()">
Add Sale
</button>
</div>
</form>
thanks in advanced!!
You have to put 'amount' in choices array.
$scope.choices = [{ id: 'choice1', amount: 0}];
Then in controller:
$scope.changedValue = function (choise,item,quan)
choise.amount = parseFloat(data.price * quan);
And in tempalte:
ng-change="changedValue(choise,selected_id,quantity)">
<input type="text" class="form-control" id="amount" ng-model="choise.amount" ng-readonly="true" />

How to validate element directive in angularjs

I want to validate multi-select in angularjs. At least one item should be selected in multi-select. If not then submit button should not enable. I am using require to validate the form. I am able to make compulsory selection of first name by using require, but how do also compulsory for multiselect.
Form
<form ng-submit='addStudent()' name='studentForm' novalidate="">
<div class="col-md-4">
<div class="col-md-12">
<label for="Name">First Name *</label>
<input ng-model='student.first_name' name="name" type="text" placeholder="First Name" required class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="col-md-12">
<label for="Name">Last Name </label>
<input ng-model='student.last_name' name="name" type="text" placeholder="Last Name" class="form-control">
</div>
</div>
<multi-selection selectedsubjs="student.selectedSubjects"
allsubjects="allSubjects"
left-title="All Subjects"
right-title="Selected Subjects">
</multi-selection>
<input ng-disabled="sutudentForm.$invalid" type="submit">
</form>
Element Directive
app.directive('multiSelection', function(){
return {
restrict: 'E',
scope: {
allsubjects: '=',
selectedsubjs: '=',
displayAttr: '#',
leftTitle: '#',
rightTitle: '#'
},
templateUrl: "templates/multiSelection.html",
link: function(scope) {
scope.swapsubject1 = function(item) {
var index = scope.allsubjects.indexOf(item);
scope.allsubjects.splice(index, 1);
scope.selectedsubjs.push(item);
}
scope.swapsubject2 = function(item) {
var index = scope.selectedsubjs.indexOf(item);
scope.selectedsubjs.splice(index, 1);
scope.allsubjects.push(item);
}
}
};
});
Multi-Select Template
<tr>
<td>
<div class="entBox">
<switchitem ng-repeat="subj in allsubjects" value="subj.name" ng-click="swapsubject1(item)" ng-model="allSubjects"></switchitem>
</div>
</td>
<td>
<div class="entBox">
<switchitem ng-repeat="subj in selectedsubjs" value="subj.name" ng-click="swapsubject2(item)" ng-model="student.selectedSubjects"></switchitem>
</div>
</td>
</tr>
Check this element is not a input type then set
if (!element.isInput()) {
element[0].setCustomValidity(errorMsg);
}
reference

AngularJS comparing two input values doesn't work as expected

I am trying to compare two password values using AngularJS. I have the submit button disabled until all the fields are valid. However, it is not working like it is supposed to. As soon as I enter the email and the first password, the submit button becomes enabled. But if I type something else in the second password field, then the submit button becomes disabled again. How do I do the validation even when nothing is entered in the second password field?
Here, is my form.
<form ng-submit="submit()" name="register" class="form-signin" novalidate>
<h1 class="form-signin-heading text-muted">
Register
</h1>
<input name="email" ng-model="email" type="email" class="form-control" placeholder="Email address" required>
<p class="help-block" ng-show="register.email.$dirty && register.email.$invalid">Please enter a valid email</p>
<input name="password" ng-model="password" type="password"class="form-control" placeholder="Password" required>
<input name="password_confirm" ng-model="password_confirm" type="password" class="form-control" placeholder="Confirm Password" validate-equals='password'>
<p class="help-block" ng-show="register.password_confirm.$dirty && register.password_confirm.$invalid">The passwords do not match</p>
<button ng-disabled="register.$invalid" class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
And here is the Javascript file(validateEquals.js)
'use strict';
angular.module('jwtApp').directive('validateEquals', function () {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
function validateEqual(value) {
var valid = (value === scope.$eval(attrs.validateEquals));
ngModelCtrl.$setValidity('equal', valid);
return valid ? value : undefined;
}
ngModelCtrl.$parsers.push(validateEqual);
ngModelCtrl.$formatters.push(validateEqual);
scope.$watch(attrs.validateEquals, function() {
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
});
}
};
});
If I can make a suggestion - do this:
<button ng-disabled="register.$invalid || password != password_confirm" class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
And not use the validateEqual implementation in your directive. Here's a fiddle: http://jsfiddle.net/jochenvanwylick/U3pVM/13972/ with your code and the fix. I wouldn't make it into a directive, nor would I try to hook into the $parsers and $formatters for the element.
try this
.directive('validateEquals', [function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
var firstPassword = '#' + attrs.validateEquals;
elem.add(firstPassword).on('keyup', function () {
scope.$apply(function () {
var v = elem.val()===$(firstPassword).val();
ctrl.$setValidity('inputmatch', v);
});
});
}
}
on html you can check like this
<input type="password" id="input1" name="input1" ng-model="input1" ng-required/>
<input type="password" id="input2" name="input2" ng-model="input2" ng-required validate-equals="input1"/>
hope will help this solution :)
EDIT
can show error message like this
<div ng-show="myForm.$error">
<span ng-show="myForm.input2.$error.inputmatch">
Passwords don't match.
</span>
</div>

Categories