Radio button event not getting fired second time - angularjs

I have two radio buttons 1. employee 2 customer when i have to select employee employee id textbox should get open n wen i click on customer it should get disappear. when i am clicking it for first tym its working fine second time its not working .
HTML FILE
<div class="row control-group">
<label >
<input name="cssPre" id="css1" value="geEmp" class="input-xlarge" type="radio" data-ng-model="addUser.Emp" ng-change="ge()">{{::'label.addUser.employee'|translate}}
</label>
<label >
<input name="cssPre" id="css2" value="customer" type="radio" data-ng-model="addUser.customer" ng-change="customer()">{{::'label.addUser.Customer'|translate}}
</label>
Textbox which i wanna show
<div ng-show="ge == true">
<div class="row control-group" ng-show="addUser.geEmp" ng-class="{error:addUserForm.phone.$dirty && !addUserForm.phone.$valid && !addUserForm.phone.$error.pattern, success:addUserForm.phone.$valid}">
<label class="col-xs-4 col-sm-4 col-md-3 col-lg-3 control-label">{{::'label.addUser.SSO'|translate}}</label>
<div class="col-xs-7 col-sm-7 col-md-9 col-lg-9 controls">
<input type="text"
class="input-xlarge"
id="sso"
name="phone"
ng-model="addUser.user.phone"
ng-pattern="ph_numbr"
placeholder="{{::'placeholder.addUser.phone'|translate}}"
ng-change="addUserForm.phone.$setValidity('duplicateName', true);"
required="true"
ng-maxlength=8
ng-minlength=8
ge-auto-focus
/>
<span class="help-block" ng-show="addUserForm.phone.$dirty && addUserForm.phone.$error.required">{{::'error.required'|translate}}</span>
<span class="help-block" ng-show="addUserForm.phone.$dirty && addUserForm.phone.$error.pattern">{{::'error.number'|translate}}</span>
<span class="help-block" ng-show="addUserForm.phone.$dirty && addUserForm.phone.$error.maxlength">{{::'error.max.length'|translate}}</span>
<span class="help-block" ng-show="addUserForm.phone.$dirty && addUserForm.phone.$error.duplicateName">{{::'error.editOrganization.duplicateName'|translate}}</span>
</div>
</div>
JS file
$scope.ge = function() {
$scope.ge = true;
}
$scope.customer = function() {
$scope.ge = false;
}

You have defined variable as well as a function as ge rename either of these one.
You are refining the $scope.ge variable as per your code
$scope.ge = function () {
$scope.ge = true;
}
So change to
$scope.someProperFunctionName = function () {
$scope.ge = true;
}
HTML
<input name="cssPre" id="css1" value="geEmp" class="input-xlarge" type="radio" data-ng-model="addUser.Emp" ng-change="someProperFunctionName ()">

Related

AngularJS ng-repeat 'No Results' div visibility flickering on second button click

The following form shows a list of data on submit. I am trying to show no results found when there is no data on submit. It works okay. But when there is data available to list, "no results" shows up for a second when i click. I tried using display:none; but it did not work. How to stop it from showing.
HTML
<form class="form-inline" name="myForm" >
<div class="form-group" >
<label class="radio-inline">
<input name="sampleinlineradio" value="3" type="radio" ng-model="radioption"
ng-required="!radioption"> MAIN 1</label>
<label class="radio-inline">
<input name="sampleinlineradio" value="1" type="radio" ng-model="radioption" >
Main 2</label>
<div ng-show="!radioption && buttonClicked">Please select one.</div>
</div>
<div class="form-group">
<label ng-repeat="branch in branches">
<input type="checkbox" name="selectedBranches[]" value="{{branch.value}}"
ng-model="branch.selected" ng-required="isOptionsRequired()" >
{{branch.name}}</label>
<div ng-show="isOptionsRequired() && buttonClicked">Please select one.</div>
</div>
<div>
<label class="searchlabel">
<input type="radio" name="searchradio1" value="showComponentSearch" ng-model="value"
ng-required="value == 'showComponentSearch'" >
Search By Component</label>
<input type="text" name="comptext" ng-model="search" id="tags"
ng-required = "value == 'showComponentSearch' && search == 'comptext'" >
<div ng-show="value == 'showComponentSearch' && !search && buttonClicked">Please enter text before submit.</div>
<div>
<label class="searchlabel">
<input name="searchradio2" value="showDateRangeSearch" type="radio" ng-model="value"
ng-required="value == 'showDateRangeSearch'" >
Search By Time</label>
</div> </div>
<div ng-show="!value && buttonClicked">Please select one search option.</div>
<input type="button" ng-click="fetchresults()" value="submit" >
</form>
<div ng-show="buttonClicked">
<table> <thead>.....</thead>
<tbody>
<tr ng-show="results.length!=0" ng-repeat="r in results">
<td></td></tbody></table>
</div>
<div ng-show="buttonClickedAgain">
<span ng-show="results.length==0 ">No results.</span>
</div>
In Controller
$scope.fetchresults = function(){
if($scope.searchSelectionValue == 'showComponentSearch') {
$scope.results = Result.query({main: $scope.radioption, branch: $scope.selection[0],
component:$scope.search });
if($scope.search) {
$scope.buttonClickedAgain = true;
}
}
$scope.buttonClicked = true;
};
You can try adding the line $scope.buttonClickedAgain = false; before the if statement as below.
$scope.fetchresults = function(){
$scope.buttonClickedAgain = false;
if($scope.searchSelectionValue == 'showComponentSearch') {
Result.query({main: $scope.radioption, branch: $scope.selection[0], component: $scope.search }, function(results){
$scope.results = results;
$scope.buttonClickedAgain = true;
});
//if($scope.search) {
//$scope.buttonClickedAgain = true;
//}
}
$scope.buttonClicked = true;
};
You can check the below snippet where result will come after 5 seconds. But when you click the button, no results div hides immediately. You can try this with multiple clicks. If it does not work properly to you then its because of other code issue which throws error and check your browser console.
var app = angular.module('app', []);
app.controller('TestController', function($scope, $timeout){
$scope.fetchresults = function(){
$scope.buttonClickedAgain = false;
if($scope.value == 'showComponentSearch') {
//$scope.results = Result.query({main: $scope.radioption, branch: $scope.selection[0],
// $scope.search });
$scope.results = [];
$timeout(function() {
var rnd = Math.random();
if(rnd >= 0.5) {
$scope.results = [{id: 1}, {id: 2}];
}
//if($scope.search) {
$scope.buttonClickedAgain = true;
// }
}, 5000);
}
$scope.buttonClicked = true;
};
});
angular.bootstrap(document, ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="TestController" >
<form class="form-inline" name="myForm">
<div class="form-group" >
<label class="radio-inline">
<input name="sampleinlineradio" value="3" type="radio" ng-model="radioption"
ng-required="!radioption"> MAIN 1</label>
<label class="radio-inline">
<input name="sampleinlineradio" value="1" type="radio" ng-model="radioption" >
Main 2</label>
<div ng-show="!radioption && buttonClicked">Please select one.</div>
</div>
<div class="form-group">
<label ng-repeat="branch in branches">
<input type="checkbox" name="selectedBranches[]" value="{{branch.value}}"
ng-model="branch.selected" ng-required="isOptionsRequired()" >
{{branch.name}}</label>
<div ng-show="isOptionsRequired() && buttonClicked">Please select one.</div>
</div>
<div>
<label class="searchlabel">
<input type="radio" name="searchradio1" value="showComponentSearch" ng-model="value"
ng-required="value == 'showComponentSearch'" >
Search By Component</label>
<input type="text" name="comptext" ng-model="search" id="tags"
ng-required = "value == 'showComponentSearch' && search == 'comptext'" >
<div ng-show="value == 'showComponentSearch' && !search && buttonClicked">Please enter text before submit.</div>
<div>
<label class="searchlabel">
<input name="searchradio2" value="showDateRangeSearch" type="radio" ng-model="value"
ng-required="value == 'showDateRangeSearch'" >
Search By Time</label>
</div> </div>
<div ng-show="!value && buttonClicked">Please select one search option.</div>
<input type="button" ng-click="fetchresults()" value="submit" >
</form>
<div ng-show="buttonClicked">
Records:
<table> <thead></thead>
<tbody>
<tr ng-show="results.length!=0" ng-repeat="r in results">
<td>{{r.id}}</td></tbody></table>
</div>
<div ng-show="buttonClickedAgain">
<span ng-show="results.length==0 ">No results.</span>
</div>
</div>
Use ng-if instead of ng-show on the div . ng-if prevents the div from being rendered
<div ng-show="buttonClickedAgain">
<span ng-show="results.length==0 ">No results.</span>
</div>

how to error message on submitting of a from in angular js

I want to show the required error message once the from is submitted but not sure how to do it i am trying as shown below
<div class="controls">
<form name="formx" >
<ul class="form small">
<div class="tag">ID</div>
<input type="text" class="small" name="enrolmentId" ng-model="enrolmentDetail.Id" required="" onkeypress='return !(event.charCode == 32 )'>
<div class="error text-danger" style="position: absolute;margin-left: 120px;" ng-show="formx.enrolmentId.$error.required && (formx.$submitted || formx.enrolmentId.$touched)"><p>Id is required</p></div>
</li>
<li>
<div class="btn" ng-click="saveDetails(enrolmentDetail)" ng-show="formAction=='save'">SAVE</div>
</li>
</ul>
</form>
</div>
here now the error message is shown once we dirty the textbox but i want to show the error message once the form is submitted and if there is required error from should not be submitted
trying used ng-submit but not sure how to do it
Please help by creating a fiddle or posting a example to do it
This is an example
html
<body ng-app="myApp">
<div ng-controller="myCtrl as mc">
<form class="form" name="myForm" ng-submit="mc.submit(myForm)" novalidate>
<div class="form-group">
<label for="username">Username</label>
<input name="username" class="form-control" type="text" ng-model="mc.username" required/>
<p class="text-danger" ng-show="myForm.username.$error.required && mc.submitted">Username is required</p>
</div>
<div class="form-group">
<label for="password">Password</label>
<input name="password" class="form-control" type="password" ng-model="mc.password" required/>
<p class="text-danger" ng-show="myForm.password.$error.required && mc.submitted">Password is required</p>
</div>
<button class="btn btn-success">submit</button>
</form>
<p class="text-success" ng-show="mc.sent && mc.submitted">Form sent</p>
js
angular.module("myApp",[])
.controller("myCtrl", function(){
var vm = this;
vm.submit = submit;
function submit(form){
vm.submitted = true;
if(form.$valid && vm.submitted === true){
//Send data logic
vm.sent = true;
}
}

How to show error messages for Checkbox set and Radio set using ng-messages?

I have been trying to validate Checkbox set and Radio set and show the error messages using ng-messages directive but it does not work out as expected. The ng-messages does not show the error message at all. I am populating error messages using an html file. Up until the errors are resolved, the submit button will be disabled in my form.
How can I show error messages for the Checkbox set and Radio set when:
One option is not selected in Radio set?
At least one option is not selected in Checkbox set?
Scaling the check for the Checkbox set so that we can check at least 2 or more are checked, etc.?
Here's my form:
<form name="userForm" ng-submit="submitForm()" novalidate>
<div class="form-group" ng-class="{ 'has-error' : userForm.subscribe.$invalid && !userForm.subscribe.$touched }">
<label class="checkbox-inline">
<input type="checkbox" id="subscribe1" value="option1" name="subscribe[]" ng-model="user.subscribe" required> 1
</label>
<label class="checkbox-inline">
<input type="checkbox" id="subscribe2" value="option2" name="subscribe[]" ng-model="user.subscribe" required> 2
</label>
<label class="checkbox-inline">
<input type="checkbox" id="subscribe3" value="option3" name="subscribe[]" ng-model="user.subscribe" required> 3
</label>
<div class="help-block" ng-messages="userForm.subscribe.$error" ng-show="userForm.subscribe.$invalid">
<div ng-messages-include="home/messages.html"></div>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : userForm.gender.$invalid && !userForm.gender.$touched }">
<div class="radio">
<label>
<input type="radio" name="gender" value="male" ng-model="user.gender" />
male
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="gender" value="female" ng-model="user.gender" />
female
</label>
</div>
<div class="help-block" ng-messages="userForm.gender.$error" ng-show="userForm.gender.$invalid">
<div ng-messages-include="home/messages.html"></div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-success " ng-disabled="userForm.$invalid">Submit</button>
</form>
messages.html
<span ng-message="required">This field is required</span>
<span ng-message="minlength">This field is too short</span>
<span ng-message="maxlength">This field is too long</span>
<span ng-message="required">This field is required</span>
<span ng-message="email">This needs to be a valid email</span>
controller.js
angular.module('myApp', ['ngRoute', 'ngAnimate', 'ngMessages']);
angular
.module('myApp')
.controller('HomeCtrl', HomeCtrl);
HomeCtrl.$inject = ['$scope'];
function HomeCtrl($scope) {
$scope.userForm = {};
}
Payment Checkbox set:
<div class="form-group" ng-class="{ 'has-error' : userForm.payment.$invalid && userForm.payment.$touched }">
<label class="checkbox-inline">
<input type="checkbox" id="payment1" value="Visa" name="payment" ng-blur="doTouched()" ng-model="user.payment[1]" ng-required="!someSelected(user.payment)"> Visa
</label>
<label class="checkbox-inline">
<input type="checkbox" id="payment2" value="Mastercard" name="payment" ng-blur="doTouched()" ng-model="user.payment[2]" ng-required="!someSelected(user.payment)"> Mastercard
</label>
<label class="checkbox-inline">
<input type="checkbox" id="payment3" value="Cash" name="payment" ng-blur="doTouched()" ng-model="user.payment[3]" ng-required="!someSelected(user.payment)"> Cash
</label>
<div class="help-block" ng-messages="userForm.payment.$error" ng-show="userForm.payment.$invalid && userForm.payment.$touched">
<div ng-messages-include="home/messages.html"></div>
</div>
</div>
Check this sample:
http://plnkr.co/edit/2w0lIf?p=preview
The check boxes list use the ng-required directive with the someSelected function (defined in the controller) which checks if at least one item is selected:
<div class="form-group" ng-class="{ 'has-error' : userForm.subscribe.$invalid && userForm.subscribe.$touched }">
<label class="checkbox-inline">
<input type="checkbox" id="subscribe1" value="option1" name="subscribe" ng-blur="doTouched()" ng-model="user.subscribe[1]" ng-required="!someSelected(user.subscribe)"> 1
</label>
<label class="checkbox-inline">
<input type="checkbox" id="subscribe2" value="option2" name="subscribe" ng-blur="doTouched()" ng-model="user.subscribe[2]" ng-required="!someSelected(user.subscribe)"> 2
</label>
<label class="checkbox-inline">
<input type="checkbox" id="subscribe3" value="option3" name="subscribe" ng-blur="doTouched()" ng-model="user.subscribe[3]" ng-required="!someSelected(user.subscribe)"> 3
</label>
<div class="help-block" ng-messages="userForm.subscribe.$error" ng-show="userForm.subscribe.$invalid && userForm.subscribe.$touched">
<div ng-messages-include="messages.html"></div>
</div>
</div>
The option button group is easier and use the ng-required directive with the condition !user.gender:
<div class="form-group" ng-class="{ 'has-error' : userForm.gender.$invalid && userForm.gender.$touched }">
<div class="radio">
<label>
<input type="radio" name="gender" value="male" ng-model="user.gender" ng-required="!user.gender"/>
male
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="gender" value="female" ng-model="user.gender" ng-required="!user.gender"/>
female
</label>
</div>
<div class="help-block" ng-messages="userForm.gender.$error" ng-if="userForm.gender.$touched">
<div ng-messages-include="messages.html"></div>
</div>
</div>
The ngBlur directive resolves the issue that a check boxes list become "touched" only when all the items in list are blurred, calling doTouched() function::
$scope.doTouched = function() {
$scope.userForm.subscribe.$setTouched();
}
P.S. pay attention to correct names: userForm is the HTML name of the <form>, user is the name of the model to which is bound the form.
Here is an example I created that suites our purpose.
Our app would create multiple checkbox questions per page, and $touched didn't seem to work on input checkbox fields that all had the same name attribute.
Also the custom angular plugins/directives I've seen for checkboxes are nice (where they just bind to 1 array model) but don't seem to support 'required'.
Here i set a custom_touched event per question which I set via ng-click:
http://jsfiddle.net/armyofda12mnkeys/9gLndp5y/7/
<li ng-repeat="choice in currentquestion.choices">
<input
type="checkbox"
ng-model="choice.selected"
ng-required="!somethingSelectedInTheGroup(currentquestion.required, currentquestion.choices)"
ng-click="currentquestion.custom_touched = true;"
name="{{currentquestion.question_code}}"
id="{{currentquestion.question_code}}_{{choice.option_value}}"
value="{{choice.option_value}}"
/> {{choice.orig_option_txt}}
</li>
$scope.somethingSelectedInTheGroup = function (is_required, choices) {
if(is_required) {
for(var i = 0; i < choices.length; i++) {
var choice = choices [i];
if(choice.selected) {
return true;
}
}
return false;
} else {
return false;
}
}
Note: i originally had used <div ng-if="questionform.$dirty && questionform[currentquestion2.question_code].$invalid">
but that doesn't work out for multiple checkbox questions per form/page.

Angularjs Form Validation of a group of input

With Angular I use specific directive for validate single input field. (i.e. email, username etc.)
In this project I have this scenario:
I need to set an Advance Payment field, this Advance must be between min/max value.
To set the Advance I have three input text:
Cash
Old Car Value
Financed Advance
the sum of those three input is my Advance value.
So I need to validate Advance but I have no a single input with ng-model setted on.
What is the best way to check and validate the Advance Payment value?
I need to add a directive to all those three input fields? or is better a directive for the form?
Any suggestion will be appreciated.
jsfiddle example
(function () {
var app = angular.module("myApp", ['ngMessages']);
app.controller('myFormCtrl', function($scope) {
$scope.plan = {};
$scope.plan.advance = 0;
$scope.plan.min_advance = 3000;
$scope.plan.max_advance = 6000;
$scope.updateAdvance = function(){
var advance = 0;
if ($scope.quotationAdvanceType && !isNaN($scope.plan.quotation))
advance += $scope.plan.quotation;
if ($scope.cashAdvanceType && !isNaN($scope.plan.cash))
advance += $scope.plan.cash;
if ($scope.financedAdvanceType && !isNaN($scope.plan.financed))
advance += $scope.plan.financed;
$scope.plan.advance = advance;
}
});
})();
Just to give you (and perhaps others) another option.
To simplify, you can use a number input with its ng-model set to plan.advance. This will allow you to use the min/max attributes. You can set the input to hidden if you prefer not to display it.
<input type="number" name="advance" ng-model="plan.advance" min="{{plan.min_advance}}" max="{{plan.max_advance}}" hidden />
Then you can use the built in validation for min and max such as:
<span ng-messages="myForm.advance.$error" role="alert">
<span ng-message="min">Minimum not reached.</span>
<span ng-message="max">Maximum exceeded.</span>
</span>
Run the code snippet below to see it in action:
(function () {
var app = angular.module("myApp", ['ngMessages']);
app.controller('myFormCtrl', function ($scope) {
var advance = [];
$scope.plan = {};
$scope.plan.advance = 0;
$scope.plan.min_advance = 3000;
$scope.plan.max_advance = 6000;
$scope.reset = function(val) {
$scope.plan[val] = undefined;
$scope.updateAdvance();
};
$scope.updateAdvance = function () {
advance = [$scope.plan.quotation, $scope.plan.cash, $scope.plan.financed];
$scope.plan.advance = advance.reduce(function (a, b) {
a = a ? a : 0;
b = b ? b : 0;
return a + b;
}, 0);
}
});
})();
#import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css");
<script src="https://code.angularjs.org/1.3.15/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular-messages.min.js"></script>
<div ng-app="myApp" class="container">
<form name="myForm" ng-controller="myFormCtrl" class="form-horizontal">
<div class="form-group" ng-class="{ 'has-error' : myForm.plan.min_advance.$invalid && myForm.plan.min_advance.$touched}">
<label for="plan.min_advance" class="control-label col-xs-4 col-sm-2">Min Advance</label>
<div class="col-xs-8 col-sm-10">
<input type="number" ng-model="plan.min_advance" class="form-control" />
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : myForm.plan.max_advance.$invalid && myForm.plan.max_advance.$touched}">
<label for="plan.max_advance" class="control-label col-xs-4 col-sm-2">Min Advance</label>
<div class="col-xs-8 col-sm-10">
<input type="number" ng-model="plan.max_advance" class="form-control" />
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : myForm.surname.$invalid && myForm.surname.$touched}">
<div class="col-xs-12">
<label for="surname" class="control-label">Surname</label>
<input type="text" value="" name="surname" id="surname" ng-model="surname" ng-minlength="3" ng-mAXlength="20" required="required" class="form-control" />
<span ng-messages="myForm.surname.$error" class="help-block" role="alert" ng-show="myForm.surname.$touched">
<span ng-message="required">You forgot to enter your surname</span>
<span ng-message="minlength">Surname is too short</span>
<span ng-message="maxlength">Surname is too long</span>
</span>
</div>
</div>
<p>Set the Advance between minimun <strong>{{plan.min_advance | currency}}</strong> and maximum <strong>{{plan.max_advance | currency}}</strong>
</p>
<div class="form-group">
<label for="quotation" class="col-xs-4 col-sm-2 control-label">
<input type="checkbox" name="quotationAdvanceType" ng-model="quotationAdvanceType" ng-change="reset('quotation')"/> Quotation:
</label>
<div class="col-xs-8 col-sm-10">
<input type="number" name="quotation" ng-value="plan.quotation" ng-model="plan.quotation" ng-change="updateAdvance()" class="form-control" ng-disabled="!quotationAdvanceType" placeholder="{{'max '+ (plan.max_advance-plan.advance)}}" />
</div>
</div>
<div class="form-group">
<label for="cash" class="col-xs-4 col-sm-2 control-label">
<input type="checkbox" name="cashAdvanceType" ng-model="cashAdvanceType" ng-change="reset('cash')" /> Cash:
</label>
<div class="col-xs-8 col-sm-10">
<input type="number" name="cash" ng-value="plan.cash" ng-model="plan.cash" ng-change="updateAdvance()" class="form-control" ng-disabled="!cashAdvanceType" placeholder="{{'max '+ (plan.max_advance-plan.advance)}}" />
</div>
</div>
<div class="form-group">
<label for="financed" class="col-xs-4 col-sm-2 control-label">
<input type="checkbox" name="financedAdvanceType" ng-model="financedAdvanceType" ng-change="reset('financed')" /> Financed:
</label>
<div class="col-xs-8 col-sm-10">
<input type="number" name="financed" ng-value="0" ng-model="plan.financed" ng-change="updateAdvance()" class="form-control" ng-disabled="!financedAdvanceType" placeholder="{{'max '+ (plan.max_advance-plan.advance)}}" />
</div>
</div>
<div ng-class="{'has-error' : myForm.advance.$invalid && (quotationAdvanceType || cashAdvanceType || financedAdvanceType) && (myForm.quotation.$dirty || myForm.cash.$dirty || myForm.financed.$dirty)}">
<input type="number" name="advance" ng-model="plan.advance" min="{{plan.min_advance}}" max="{{plan.max_advance}}" hidden />
<p class="help-block">Total Advance: <strong>{{plan.advance ? (plan.advance | currency) : 'none'}}</strong>
<span ng-messages="myForm.advance.$error" role="alert" ng-show="myForm.quotation.$dirty || myForm.cash.$dirty || myForm.financed.$dirty">
<span ng-message="min">Minimum not reached.</span>
<span ng-message="max">Maximum exceeded.</span>
</span>
</p>
</div>
<button type="submit" class="btn btn-primary" ng-disabled="myForm.$invalid">Send</button>
</form>
</div>
Is there an advantage over your custom directive approach? I would say yes and here's why:
Your directive is tightly coupled to your controller scope, so you can't reuse it elsewhere in your application and it will require you to separately update it if you change one of your scope variables in the future.
You are essentially duplicating code for functionality that already exists in the framework. That results in more upfront cost of development and maintenance effort down the line.
I solve my question with a brand new directive.
I don't know if this is the right way to do that, but it works fine and the behaviour is correct.
app.directive('totalAdvance', function() {
return {
restrict: 'E',
require: '^form',
link: function(scope, element, attrs, formCtrl) {
var advanceValue = 0;
var advanceValidator = function() {
if (advanceValue >= attrs.min && advanceValue <= attrs.max){
formCtrl.$setValidity('minAdvance', true);
formCtrl.$setValidity('maxAdvance', true);
return advanceValue;
}else if (advanceValue < attrs.min) {
formCtrl.$setValidity('minAdvance', false);
formCtrl.$setValidity('maxAdvance', true);
return null;
}else if (advanceValue > attrs.max){
formCtrl.$setValidity('minAdvance', true);
formCtrl.$setValidity('maxAdvance', false);
return null;
}
};
scope.$watch('plan.advance', function(value) {
advanceValue = value;
return advanceValidator();
});
scope.$watch('plan.min_advance', function() {
return advanceValidator();
});
scope.$watch('plan.max_advance', function() {
return advanceValidator();
});
}
};
});
jsfiddle example

AngularJs : Check some fields are valid then fire ajax and populate the select html

I've a form below
<form class="form-horizontal" role="form" name="req_appmt" id="req_appmt" novalidate ng-submit="SendAppointmentRequest()">
<div class="form-group" ng-class="(req_appmt.form_comments.$error.required) ? 'has-error' : '' ">
<label for="form_comments" class="col-lg-2 control-label">Reason for Appointment* :</label>
<div class="col-lg-10"><textarea id="form_comments" name="form_comments" ng-model="formdata.form_comments" class="form-control" rows="3" required></textarea></div>
</div>
<div class="form-group" ng-class="(req_appmt.physician_id.$error.required) ? 'has-error' : '' ">
<label for="physician_id" class="col-lg-2 control-label">To* :</label>
<div class="col-lg-10">
<select name="physician_id" ng-model="formdata.physician_id" id="physician_id" class="form-control" required>
<option value="">--Select--</option>
<option ng-repeat="physician in physicians" value="{{physician.id}}">{{physician.fullname}}</option>
</select>
</div>
</div>
<div class="form-group" ng-class="(req_appmt.date.$error.required) ? 'has-error' : '' ">
<label for="inputEmail1" class="col-lg-2 control-label">Date :</label>
<div class="col-lg-10">
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="dd-MM-yyyy" ng-model="formdata.date" name="date" is-open="opened" min-date="minDate" close-text="Close" required="required" ng-click="open($event)">
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
</div>
<div class="form-group" ng-class="(req_appmt.time.$error.required) ? 'has-error' : '' ">
<label for="inputEmail1" class="col-lg-2 control-label">Free Slot :</label>
<div class="col-lg-10">
<select name="time" ng-model="formdata.time" id="time" class="form-control" required>
<option value="">--Select--</option>
<!-- <option ng-repeat="key,value in slots" value="{{value}}">{{value}}</option> -->
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10"><p>
<button type="submit" class="btn btn-primary btn-lg btn-success">Request Appointment</button>
Cancel
</p> </div> </div>
</form>
This is my controller :
ModuleEvents.controller('ctrlRequestAppointment', function ($location,$scope,$http,$rootScope,$cookies,ServiceCheckAuth,ServiceEvents){
/*First check patient is logged in*/
if( !ServiceCheckAuth.isPatientLoggedIn() ){
$location.url('/login');
return;
}
/*Set rootScope values*/
$rootScope.root = {
html_title:HTML_TITLE_PATIENT_APPOINTMENT_REQUEST,
loggedin:true,
activeNxtstp:'active',
customclass:'content_inner_im w-100-mob'
};
var json_physicians = localStorage.getItem('physicians');
$scope.minDate = $scope.minDate ? null : new Date();
$scope.date = new Date();
$scope.physicians = JSON.parse(json_physicians);
$scope.formdata = {};
$scope.opened = false;
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.$watch(req_appmt.date.$valid, function() {
if( req_appmt.date.$valid && req_appmt.physician_id.$valid ){
console.log($scope.formdata);
}
});
$scope.SendAppointmentRequest = function(){
if( $scope.req_appmt.$valid ){
console.log($scope.formdata);
}
}
});
What I'm trying :
1) User selects To field in the form
2) then user selects date field in the form
3) then I want to check in controller both are filled and validated
4) then I want to fire a ajax request that will populate the Free Slot field of he form
Problem :
I can not check whether the fields are valid
Any help is greatly appreciated
Thanks
can you use an function() which can validate all fields of formdata like
$scope.function_name=function()
{
var validatefalg=true;
if($scope.formdata.physician_id!='')
{
validatefalg=false;
return validatefalg;
}
else
{
return validatefalg;
}
}
I solve my problem with the help of #jyotsna :
if( $scope.req_appmt.physician_id.$valid && $scope.req_appmt.date.$valid ){}

Resources