Angular auto form submit on validate with $watch - javascript

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/

Related

count number of required field in form in angular js?

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>

AngularJs Input textbox allow only greater than zero value

I am trying validate the textbox allow only integer number and greater than zero values.
Here I attached my code.
Html:
<body ng-app="myApp">
NUMBER ONLY <input type="text" allow-pattern="\d" />
</body>
Js:
var app = angular.module("myApp",[]);
app.directive('allowPattern', [allowPatternDirective]);
function allowPatternDirective() {
return {
restrict: "A",
compile: function(tElement, tAttrs) {
return function(scope, element, attrs) {
element.bind("keypress", function(event) {
var keyCode = event.which || event.keyCode; // I safely get the
if (!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))) {
event.preventDefault();
return false;
}
});
};
}
};
}
Also I tried like this bellow:
<body ng-app="myApp">
NUMBER ONLY <input type="text" allow-pattern="^[1-9][0-9]*$" />
</body>
But its not working.
Check jsfiddle link: click here
You can make use of angular form validation and also use ng-model-options
Here is the link to Codepen
Controller snippet :
var app = angular.module('app',[]);
app.controller('myCtrl',function($scope){
$scope.onlyNumbers = /^[1-9]+[0-9]*$/;
})
View :
<div ng-app="app">
<br />
<br />
<div class="col-md-2" ng-controller="myCtrl">
<form name="myForm1">
<div class="form-group" ng-class="{'has-error':myForm1.number1.$invalid}">
<label for="">Following validation happens as the user entrs a value.</label>
<input class="form-control" ng-pattern="onlyNumbers" ng-model="value1" name="number1"/> Valid? {{myForm1.number1.$valid}}
</div>
</form>
<form name="myForm2">
<div class="form-group" ng-class="{'has-error':myForm2.number2.$invalid}">
<label for="">Following validation happens after blur </label>
<input class="form-control" ng-pattern="onlyNumbers" ng-model="value2" name="number2" ng-model-options="{ updateOn: 'blur'}"/> Valid? {{myForm2.number2.$valid}}
</div>
</form>
For more on how you can better this process through controllers refer this link

angular validation not working on select

its a simple form a drop down and a save button. On page load Select should be ng-invalid because it is required and nothing is selected but form and select both are ng-valid and save function is called.
and once i select any thing and un select it. then it behaves properly.
<form role="form" name="frmVariableConfig" id="frmVariableConfig" novalidate ng-submit="frmVariableConfig.$valid && saveChanges()">
<div>
<div class="form-group">
<div class="form-group control-group">
<span>Logic</span>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="CurrCustomer.Logic"
ng-options="service.ServiceID as service.ServiceName for service in services"
required="">
<option value="">Select Service</option>
</select>
</div>
</div>
</div>
<div>
<button type="submit" class="btn btn-sm text-right">Save</button>
</div>
</form>
where the controller code looks like this.
(function () {
'use strict';
var controllerId = 'dashboard';
angular.module('app').controller(controllerId, ['$scope', dashboard]);
function dashboard($scope) {
$scope.CurrCustomer = {};
$scope.CurrCustomer.Logic = false;
$scope.saveChanges = function () {
alert('function called');
};
$scope.services = [
{ ServiceID: 1, ServiceName: 'Service1' },
{ ServiceID: 2, ServiceName: 'Service2' },
{ ServiceID: 3, ServiceName: 'Service3' }
];
}})();
You need to remove the setter $scope.CurrCustomer.Logic = false; from your controller that is filling that ng-model and making it valid on controller load. After filling that CurrCustomer.Logic value it become valid input as it is required.

re enabling ng-disabled button in Angular JS

I am a newbie to AngularJS. I have created a form with fields which is disabled using ng-disabled by default. when I click on the edit <button> I want these fields to re-enable.
HTML
<form class="form-horizontal" role="form" ng-submit="edit_setting()" ng-controller="ExchangeController">
<div class="form-group">
<label>Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.name" ng-disabled="true">
</div>
</div>
<div class="form-group">
<label>Host Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.host_name" required ng-disabled="true">
</div>
</div>
<div class="form-group">
<label>Address</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.address" ng-disabled="true">
</div>
</div>
</form>
Controller
function ExchangeController($scope, $http, $cookieStore, $location) {
var edit_exchange_setting = "https://pvbp.com/api/settings.html?contactid=292351&exchange_id=7124&clearinghouseid=1&token=e5349652507c0esae86d50fdbdc53222cf97&page=view";
$http.get(edit_exchange_setting).success(function(response){
$scope.exchange_dt.exchange_name = response.name;
$scope.exchange_dt.exchange_host_name = response.host_name;
$scope.exchange_dt.exchange_last_processed_date = response.address;
});
$scope.edit_exchange_setting_click = (function(){
// how can i make the fields re enable here
});
}
in controller create scope variable,
$scope.disabled= true;
and replace all ng-disabled with that variable like,
...ng-model="exchange_dt.name" ng-disabled="disabled"....
when you click on edit button set $scope.disabled to false like,
$scope.edit_exchange_setting_click = (function(){
$scope.disabled = false;
});
you can have a scope variable keeping the true or false value.and a setter for that variable.
function ExchangeController($scope, $http, $cookieStore, $location) {
var edit_exchange_setting = "https://pvbp.com/api/settings.html?contactid=292351&exchange_id=7124&clearinghouseid=1&token=e5349652507c0esae86d50fdbdc53222cf97&page=view";
$http.get(edit_exchange_setting).success(function(response){
$scope.exchange_dt.exchange_name = response.name;
$scope.exchange_dt.exchange_host_name = response.host_name;
$scope.exchange_dt.exchange_last_processed_date = response.address;
});
$scope.edit_exchange_setting_click = (function(){
// how can i make the fields re enable here
});
$scope.dtName=true;
$scope.isdtNameDisabled=function()
{
return $scope.dtName;
};
$scope.updatedtName=function(flag)
{
$scope.dtName=flag;
};
}
and in your HTML you can bind that getter function.
<div class="form-group">
<label>Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.name" ng-disabled="isdtNameDisabled()>
</div>
</div>
You need to create a variable at the top of controller say
$scope.mydisabled=true;
then set your ng-disable with the variable
ng-disabled="mydisabled"
and on click of edit button set its value to false
$scope.mydisabled=false;
UPDATE
Fiddle
A different (however similar) approach is to wrap your form contents in a fieldset and have ng-disabled in the fieldset only rather than in all the input fields. To make the html more cleaner.
<form class="form-horizontal" role="form" ng-submit="edit_setting()" ng-controller="ExchangeController">
<fieldset ng-disabled ="isFormSetForSaving">
<div class="form-group">
<label>Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.name">
</div>
</div>
<div class="form-group">
<label>Host Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.host_name" required>
</div>
</div>
<div class="form-group">
<label>Address</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.address">
</div>
</div>
</fieldset>
</form>
and now in the controller set the isFormSetForSaving to true/false as per your logic.
function ExchangeController($scope, $http, $cookieStore, $location) {
$scope.isFormSetForSaving = true;
var edit_exchange_setting = "https://pvbp.com/api/settings.html?contactid=292351&exchange_id=7124&clearinghouseid=1&token=e5349652507c0esae86d50fdbdc53222cf97&page=view";
$http.get(edit_exchange_setting).success(function(response){
$scope.exchange_dt.exchange_name = response.name;
$scope.exchange_dt.exchange_host_name = response.host_name;
$scope.exchange_dt.exchange_last_processed_date = response.address;
});
$scope.edit_exchange_setting_click = (function(){
// how can i make the fields re enable here
$scope.isFormSetForSaving = false;
});
}

Why won't this from scope variable at Angular JS controller is set to true?

I'm trying to code a controller so some inputs get disabled after changes in another one.
This is the controllre:
app.controller('SignUpController',function ($scope, $http) {
this.unavaliable = true
this.userUnavaliable = function() {
console.log(this.unavaliable)
return this.unavaliable
}
this.userExists = function(mail) {
if (mail) {
var who = $http.get("/existingUsers/"+mail)
who.success(function(data,status, headers, config) {
if (data.mail) {
this.unavaliable = true
console.log(data.mail + " ya existe en la DB")
}
else{
this.unavaliable = false
}
});
who.error(function(data, status, headers, config) {
alert("AJAX failed!");
})
}
}
})
As my markup below shows, one input should obtain a certain class, and another one should get disabled when unavaliable is set to true. But even I can get to the console.log(), the variable seems to never get true.
This is my markup:
<form class="form-inline" role="form">
<div class="form-group">
<input type="email" class="form-control input-lg" ng-model="signup.mail" placeholder="e-mail" ng-change="signup.userExists(signup.mail)" ng-class="{'has-error':signup.userUnavaliable()}">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" placeholder="ContraseƱa" ng-nodel="signup.password">
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="signup.role" value="admin"> Administrador
</label>
</div>
<button type="submit" class="btn btn-primary" ng-disabled="signup.unavaliable" >Registrar</button>
</form>
I tried with $scope instead of this but never got it to work that way
Try this:
app.controller('SignUpController',function ($scope, $http) {
var that = this;
that.unavaliable = true;
that.userUnavaliable = function() {
console.log(that.unavaliable)
return that.unavaliable
}
that.userExists = function(mail) {...
Your issue seems to be related to JS Context; in the example above it is preserved in that variable. That is how it is done in JOhn's Papa approach

Categories