NgFormModel NgControl read value - angularjs

I have a form where I have already values in the input text field. After the submit button (changes) the unchanged input field returns a empty string in the json object.
//the component
this.builder = fb;
this.EditUserForm = this.builder.group({
firstName: ["", Validators.required],
lastName: ["", Validators.required],
});
<form [ngFormModel]="EditUserForm" (submit)="saveChanges($event)">
<div class="col-xs-2">
<label for="firstname">First Name</label>
<input class="form-control" id="firstname" ngControl="firstName" type="name" required value={{person.firstName}}>
</div>
<div class="col-xs-2" >
<label for="lastname">Last Name</label>
<input class="form-control" id="lastname" ngControl="lastName" type="name" required value={{person.lastName}}>
</div>
<div class="container">
<button type="submit" class="btn btn-primary">Save Changes</button>
</div>
</form>
As you can see I have already values in the input. But the ngControl does not take this. Only when I put a change value in the input text field. It shows the value person.firstname but does not read it in ngControl

Other answer would be (with your setup),
You can make use of [(ngModel)] directive which actally binds your value to input control and updates ngCtrl status.
<input ... [(ngModel)]="person.firstName" #firstName="ngForm" ...>
Look at here working example of the same,
https://plnkr.co/edit/hvAG3lLpfP80U9hMKAEA?p=preview

you have to use [ngFormControl] for binding the controls in the template.
//the component
this.builder = fb;
this.EditUserForm = this.builder.group({
firstName: ["", Validators.required],
lastName: ["", Validators.required],
});
<form [ngFormModel]="EditUserForm" (submit)="saveChanges(EditUserForm.values)">
<div class="col-xs-2">
<label for="firstname">First Name</label>
<input class="form-control" id="firstname" [ngFormControl]="EditUserForm.controls['firstname']" type="name" required value={{person.firstName}}>
</div>
<div class="col-xs-2" >
<label for="lastname">Last Name</label>
<input class="form-control" id="lastname" [ngFormControl]="EditUserForm.controls['lastname']" type="name" required value={{person.lastName}}>
</div>
<div class="container">
<button type="submit" class="btn btn-primary">Save Changes</button>
</div>
</form>

Related

How to display error message when passwords doesn't match in Angularjs?

I'm new at Angularjs and my question is how to display an error message when the password doesn't match with confirm password?
Can someone help me, this is not very difficult but I'm still learning to programme.
Thanks to everyone!
I have html code:
<form ng-submit="saveItem(userForm.$valid)" name="userForm">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="database_address">User</label>
<input type="text" class="form-control" required ng-model="activeItem.username" placeholder="Потребителско Име..." />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="text" class="form-control" id="password" ng-model="activeItem.passwordString" />
</div>
<div class="form-group">
<label for="password">Confirm Password</label>
<input type="text" class="form-control" id="password" ng-model="activeItem.passwordConfirm" />
</div>
<p ng-show="(userForm.passwordConfirm != '') && (userForm.password != userForm.passwordConfirm)">Passwords don't match</p>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="username">Operator</label>
<input type="text" class="form-control" required id="username" ng-model="activeItem.name" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Save</button>
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
And angular function:
$scope.saveItem = function(){
console.log($scope.activeItem);
//delete $scope.activeItem.hash_method
var objectToSave = {
username: $scope.activeItem.username,
//password: $scope.activeItem.password,
name: $scope.activeItem.name,
id: $scope.activeItem.id
};
if($scope.activeItem.passwordString != ''){
if($scope.activeItem.passwordString == $scope.activeItem.passwordConfirm){
objectToSave.password = $scope.activeItem.passwordString;
} else {
console.log('Confirm password error');
}
}
You'll want to keep different Id's for the two password fields, also take a look at your model bindings:
<input type="text" class="form-control" id="password" ng-model="activeItem.passwordString" />
<input type="text" class="form-control" id="passwordConfirm" ng-model="activeItem.passwordConfirm" />
You can just reference the items that are bound with ng-model within an ng-if/ng-show, and then you shouldn't need any custom logic on the back-end.
<p ng-show="(activeItem.passwordString && activeItem.passwordConfirm) && activeItem.passwordString
!== activeItem.passwordConfirm ">Passwords don't match</p>
Also, you'll probably want to use '!==' over '!=' since you're just comparing two strings, as it's more strict of a comparison.
Edit: one thing to note, with this direction you'll still probably want to do error checking in the save function, but this should handle displaying the error message without any issues.
Remember the operator for 'not equal' is "!==", with that you will be able to make it!

How to enable/disable button with validation in Angular JS

Expected: After Entering Valid Email ID pattern button should be enabled.
Happened: After Entering Valid Email ID button goes disabled.
This is my Input textfield in HTML:
<form class="form-inline">
<div class="form-group">
<label for="emailID">Enter Email ID</label>
<input type="email" class="form-control" id="emailID" ng-model="c.emailID" placeholder="Enter EmailID">
</div>
<div class="form-group">
<label for="Password">Enter Password</label>
<input type="password" class="form-control" id="password" ng-model="c.password" placeholder="Enter Password">
</div>
<button type="submit" ng-model="button" ng-click ="submit(c)" ng-disabled="c.emailID" class="btn btn-primary">Login</button>
This is my AngularjS Script :`
var myApp1=angular.module('myApp',[]);
myApp1.controller('myController',['$scope',function($scope)
{
$scope.submit=function(c)
{
}
}]);
First add a name to your form and to your input:
<form name="myForm" class="form-inline">
<input type="email" name="emailID" class="form-control" id="emailID" ng-model="c.emailID" placeholder="Enter EmailID">
Then change your ng-disabled:
<button type="submit" ng-model="button" ng-click ="submit(c)" ng-disabled="!(myForm.emailID.$valid && myForm.emailID.$dirty)" class="btn btn-primary">Login</button>
$dirty is added because we want the user to actually enter an value before we enable. Or you can add required on your input if its a compulsory input field.
Also refer: http://www.w3schools.com/angular/angular_validation.asp

Storing the data in array using ng-model

I want to store the data in an array using the ng-model. I have an controller as RegisterController in which i inject $scope with ng-model name as user i.e. $scope.user={}.Here i am reading the data from form input element and submitting the data that has ng-model="user.name" and now i want to store that name or the multiple values in that user object.
<form class="well" align="center">
<input ng-model="user.name" name="name" type="text"><br/>
<input ng-model="user.name" name="mobile" type="text"><br/>
<input ng-model="user.name" name="mail" type="mail"><br/>
<input ng-model="user.name" type="password" name="otp"><br/><br/>
<button type="button">Sign Up</button>
Login<br><br>
</form>
and the controller is
app.controller("RegisterController",function($scope){
$scope.user={};
})
Now let me know to store the data in the user that as array with example
I think your doing a small mistake. Instead of sending the same ng-model="user.name" send is as,
<form class="well" align="center">
<input ng-model="user.name" name="name" type="text"><br/>
<input ng-model="user.mobile name="mobile" type="text"><br/>
<input ng-model="user.mail" name="mail" type="mail"><br/>
<input ng-model="user.password" type="password" name="otp"><br/><br/>
<button type="button">Sign Up</button>
Login<br><br>
</form>
And you have to send that ng-model to the function as in button
<button type="button" ng-click="signup(user)">SignUp</button>
now you can able to get what you want
Guys it was very simple and now i get. In HTML it should be like this,
<div ng-controller="RegisterController">
<form class="well" align="center">
<input ng-model="user.name" name="name" type="text"><br/>
<input ng-model="user.mobile name="mobile" type="text"><br/>
<input ng-model="user.mail" name="mail" type="mail"><br/>
<input ng-model="user.password" type="password" name="otp"><br/><br/>
<button type="button" ng-click="signup(user)">Sign Up</button>
Login<br><br>
</form>
</div>
Now In Register Controller, i need just, an array as follows:
app.controller("RegisterController",function($scope){
$scope.regruser=[];
$scope.signup=function(user){
$scope.regruser.push(user);
}
})
Now you can get $scope.regruser where you needed. as it having all registered user.
I don't see any benefit of storing the user model in an array. Instead extend the user model with properties name, mobileNumber, email, password
$.scope.user = {
name: '',
mobileNumber: '',
email: ''
password: ''
}
And in your html bind model properties to their corresponding input fields like
<input class="form-group" name="mobile" type="text" placeholder="Enter Mobile Number" ng-model="user.name.mobileNumber"/>
And if you still need to have an array then parse the $scope.user model and extract values to array in angular controller.
HTML PART
<form class="well" align="center">
<input class="form-group" name="name" type="text" placeholder="Enter Name" ng-model="user.name"><br/>
<input class="form-group" name="mobile" type="text" placeholder="Enter Mobile Number" ng-model="user.mobile"><br/>
<input class="form-group" name="mail" type="mail" placeholder="Enter mail id" ng-model="user.mail"><br/>
<input class="form.group" type="password" name="otp" placeholder="Enter Password" ng-model="user.password"><br/><br/>
<button type="button" class="btn btn-warning btn-sm" ng-click="signUp()">Sign Up</button>
Login<br><br>
</form>
Code For Controller :
$scope.user = {
name: '',
mobile: '',
mail: '',
password: ''
};
This answer is a correction to Andrejs Abrickis answer as well. Because:
he misses comma after email
he misses semi-colon after "}"
Adds an extra dot in between $ & scope
Thanks You... Hope It Helps You all.. :)

AngularJS ngDisabled isn't activated as it should be

I have a code that should disable a button when : registerForm.$invalid || form.password != form.passwordBis, which should mean : "Disable the button if the form isn't valid OR if the '$scope.form.password' variable isn't equal to '$scope.form.passwordBis'.", isn't it?
So here I have a code that activate the button if the two passwords matches. Which shouldn't happen, because the first condition is still wrong !
HTML :
<div ng-app="app" ng-controller="formCtrl">
<form name="registerForm">
<div class="header">
<h2>Create your account</h2>
</div>
<div class="form-group">
<div class="title">First Name</div>
<input type="text" name="firstName" ng-required class="form-control" ng-class="{empty:form.firstName.length==0}" ng-model="form.firstName" required></input>
</div>
<div class="form-group">
<div class="title">Last Name</div>
<input type="text" name="lastName" ng-required class="form-control" ng-class="{empty:form.lastName.length==0}" ng-model="form.lastName" required></input>
</div>
<div class="form-group">
<div class="title">Email</div>
<input type="email" name="email" ng-required class="form-control" ng-class="{empty:form.email.length==0}" ng-model="form.email" required></input>
</div>
<div class="form-group">
<div class="title">Password</div>
<input type="password" name="password" class="form-control" ng-class="{empty:form.password.length==0}" ng-model="form.password" required></input>
<input type="password" name="passwordBis" class="form-control" ng-class="{empty:form.passwordBis.length==0}" ng-model="form.passwordBis" minlength="6" required></input>
</div>
<div ng-if="form.password != form.passwordBis" class="error">Passwords doesn't match.</div>
<div class="form-group">
<button class="btn btn-success" ng-click="register()" ng-disabled="registerForm.$invalid || form.password != form.passwordBis">Register</button><br/>
</div>
</form>
</div>
JS :
var app = angular.module("app", []);
app.controller("formCtrl", function($scope) {
$scope.form = {
firstName: "",
lastName: "",
email: "",
password: "",
passwordBis: ""
};
});
And you can test it : JSFiddle
What am I missing ?
Remove ng-required attributes from your form elements.
For form elements you should use either ng-required or required, but not both at the same time. ng-required expects an expression that needs to evaluate to true in order to mark a form element as required, whereas required doesn't need any value. See https://stackoverflow.com/a/16648851/1237995 for more detailed explanation.

$scope.formName.fieldName.$setValidity is not working

I would like to set invalid with angular when firstname is equals to lastname and change the color using styles to red.
http://jsbin.com/japir/2
function RegoController($scope) {
$scope.app = {
firstName: "Saroj"
};
$scope.$watch("app.lastName", function(newVal, oldVal) {
if (!!$scope.app.lastName && !!newVal)
if (angular.lowercase($scope.app.firstName) === angular.lowercase(newVal)) {
debugger;
$scope.form.inputLastName.$setValidity("sameName", false);
}
});
}
<body ng-app>
<div class="container" ng-controller="RegoController">
<div class="col-lg-4">
<form name="form">
<div class="form-group">
<label for="inputFirstName">First Name</label>
<input id="inputFirstName" class="form-control" type="text" ng-model="app.firstName" placeholder="Enter your firstname" required ng-minlength="3" ng-maxlength="20" />
</div>
<div class="form-group">
<label for="inputLastName">Last Name</label>
<input id="inputLastName" class="form-control" type="text" ng-model="app.lastName" placeholder="Enter your last name" required ng-minlength="3" ng-maxlength="20" />
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input id="inputEmail" class="form-control" type="email" ng-model="app.email" placeholder="Enter your email" required />
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Save" />
</div>
</form>
{{app}}
</div>
</div>
</body>
The problem is that you are trying to select a form input that has no name; thus making it unable to find the field you are trying to invalidate. Here is a working example:
JSBIN: http://jsbin.com/yozanado/1/
Input field with name:
<input id="inputLastName" name="lastName" class="form-control" type="text" ng-model="app.lastName" placeholder="Enter your last name" required ng-minlength="3" ng-maxlength="20" />
Javascript:
$scope.form.lastName.$setValidity("sameName", false);
AngularJS form validation relies on the name of the form and the name of the fields to find the validation models on scope.
For example, if your HTML is:
<form name="form">
<input name="firstName" ng-model="firstName" />
</form>
You will be able to access the validation $error property on scope using the name attributes:
$scope.form.firstName.$error.sameName
To fix the issues you're having, add a name attribute to your input fields.
JSBin Demo

Resources