Angularjs ng-if with required field validation - javascript

Hi I am developing one web application in angularjs. I have one checkbox and very next i have one dropdown. If i check checkbox then i want to make dropdown required. Wheneer i do following,
I click on checkbox-dropdown required validation will occur.
Whenever i uncheck on checkbox still my required validation will occur. I want to make required validation for dropdown only when checkbox is checked.
Below is my checkbox.
<div class="inputblock">
<label class="inputblock-label">{{ 'Military' | translate }}</label>
<label class="military">{{ 'Military' | translate }}</label>
<input type="checkbox" name="Military" placeholder="{{ 'Military' | translate }}" ng-model="Military" ng-change="statechanged(Military)">
</div>
Below is my dropdown.
<div class="inputblock" ng-class="{ 'has-error' : ((form3.$submitted && form3.rank.$invalid) || (form3.rank.$invalid && form3.rank.$dirty))}">
<label class="inputblock-label">{{ 'Rank' | translate }}</label>
<div ng-if="rankrequired==true">
<span class="ang-error" style="color:#fff" ng-show="form3.rank.$invalid && form3.rank.$error.required && form3.rank.$dirty">*{{'Required' | translate}}</span>
</div>
<select id="rank" name="rank" ng-model="user.rank" ng-options="user.ID as user.Rank for user in rankList" required>
<option value="" label="rank">{{ 'Rank' | translate }}</option>
</select>
</div>
Below is my javascript code.
$scope.statechanged = function (Military) {
if (Military == true)
{
enablerankdropdown();
$scope.rankrequired = function () {
return true;
};
}
else
{
$scope.user.rank = $scope.rankList[0].value;
disablerankdropdown();
$scope.rankrequired = function () {
return false;
};
}
}
Whenever i uncheck the checkbox i dont want to have required field validator. Now i am getting required field validator after unchecking also. May i know why this is happening here? May i get some help in order to fix the above issue? Any help would be appreciated. Thank you.

You can use ng-required to achieve this. Assign the ng-model of your checkbox to ng-required of select.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<h2>Validation Example</h2>
<form ng-app="myApp" ng-controller="validateCtrl"
name="myForm" novalidate>
<input type="checkbox" name="user" ng-model="user">
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required ng-required="user">
<option value="">Select Service</option>
</select>
<span style="color:red" ng-show="myForm.service_id.$error.required">Select service</span>
<input type="submit"
ng-disabled="
myForm.service_id.$dirty && myForm.service_id.$invalid">
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
});
</script>
</body>
</html>

You can use ng-required="Military".
<div class="inputblock" ng-class="{ 'has-error' : ((form3.$submitted && form3.rank.$invalid) || (form3.rank.$invalid && form3.rank.$dirty))}">
<label class="inputblock-label">{{ 'Rank' | translate }}</label>
<div ng-if="rankrequired==true">
<span class="ang-error" style="color:#fff" ng-show="form3.rank.$invalid && form3.rank.$error.required && form3.rank.$dirty">*{{'Required' | translate}}</span>
</div>
<select id="rank" name="rank" ng-model="user.rank" ng-options="user.ID as user.Rank for user in rankList" ng-required="Military">
<option value="" label="rank">{{ 'Rank' | translate }}</option>
</select>
</div>

Related

How to hide div based on select the dropdown in angular js

How to hide div based on select the dropdown.
Here is the sample code I have written
<div>
<p>Course Type</p>
<div>
<select name="student-type" id="student-type" class="icon-select-down" ng-model="studentType" ng-change="getOption(this)">
<option value="java" selected>Java</option>
<option value="angularjs">Angular js</option>
<option value="reactJs">React js</option>
</select>
</div>
</div>
<div ng-if="studentType">
<p>Attendence Days</p>
<div class="slice-item">
<input type="text" class="input input-text" ng-model="attendenceDays" required validate-on="blur" ng-pattern="/^([1-9]|10)$/" invalid-message="'You must enter number between 1 to 25'" />
</div>
</div>
In controller i have written below code.
$scope.getOption = function(value) {
if (value.studentType = "angularjs") {
$scope.studentType = "false";
}
};
Can any one please guide me solving this problem?
What is the issue with your code?
Its purely the logical issue. You are checking ng-if="studentType" for showing the input container. Inside the change event you are using if (value.studentType = "angularjs"). This is not a condition checking, its assignment opertator. You have to use if (value.studentType == "angularjs") or if (value.studentType === "angularjs") to compare the value value.studentType with string "angularjs". In your scenario, the if statement will always assign "angularjs" to studentType and after that the code inside if will assign "false" to studentType. There is no need to do this in this way.
You could do this in multiple ways. I suggest two options here
Option 1: Inside the template check the value for studentType. If studentType is not angularjs then only display the input. So just add a condition in ng-if="studentType !== 'angularjs'". Here you dont have to write any logic inside the controller
Working Fiddle
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
// $scope.showInput = true;
// $scope.getOption = function (value) {
// if (value.studentType == "angularjs") {
// $scope.showInput = false;
// }
// };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<p>Course Type</p>
<div>
<select name="student-type" id="student-type" class="icon-select-down" ng-model="studentType"
ng-change="getOption(this)">
<option value="java" selected>Java</option>
<option value="angularjs">Angular js</option>
<option value="reactJs">React js</option>
</select>
</div>
</div>
<div ng-if="studentType !== 'angularjs'">
<p>Attendence Days</p>
<div class="slice-item">
<input type="text" class="input input-text" ng-model="attendenceDays" required validate-on="blur"
ng-pattern="/^([1-9]|10)$/" invalid-message="'You must enter number between 1 to 25'" />
</div>
</div>
</div>
Option 2: Inside the change function, check the value of selected option. Set a visiblity boolean based on the value of selected option. Make the input visible based on that boolean
Working Fiddle
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.showInput = true;
$scope.getOption = function (value) {
$scope.showInput = value.studentType !== "angularjs";
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<p>Course Type</p>
<div>
<select name="student-type" id="student-type" class="icon-select-down" ng-model="studentType"
ng-change="getOption(this)">
<option value="java" selected>Java</option>
<option value="angularjs">Angular js</option>
<option value="reactJs">React js</option>
</select>
</div>
</div>
<div ng-if="showInput">
<p>Attendence Days</p>
<div class="slice-item">
<input type="text" class="input input-text" ng-model="attendenceDays" required validate-on="blur"
ng-pattern="/^([1-9]|10)$/" invalid-message="'You must enter number between 1 to 25'" />
</div>
</div>
</div>

Angular form submitting

I'm new in programming and need a little advice.
I create two tables in my database - Employee (with foreign key "emp_depId") and Department with values (HR, Tech, Finance). In order to create an employee I need emp_depId, but from select in my form I get depName. What can I do? I must send a request to the server and get all departments from DB and than in data binding call method with "depName" argument, which return me necessary Id. Than I'll assign it to employee.emp_DepId and save.
Here is my form:
<form novalidate #form="ngForm" (ngSubmit)="submitForm(form)" (reset)="resetForm()" >
<div class="form-group">
<label>First Name</label>
<input class="form-control" name="firstName" [(ngModel)]="employee.firstName" required />
</div>
<div class="form-group">
<label>Last Name</label>
<input class="form-control" name="lastName" [(ngModel)]="employee.lastName" required />
</div>
<div class="form-group">
<label>Department</label>
<select class="form-control" name="depName" [(ngModel)]="getDepId(department.depName)">
<option *ngFor="let depName of getDepartments(); let i = index" [value] = "depName[i]">
{{depName}}
</option>
</select>
</div>
<button type="submit" class="btn btn-primary"
[class.btn-warning]="editing" [disabled]="form.invalid">
{{editing ? "Save" : "Create"}}
</button>
<button type="reset" class="btn btn-secondary" routerLink="/">Cancel</button>
</form>
Am I right? Thank you.
As per your code you can do it like :
<select class="form-control" name="emp_DepId" [(ngModel)]="employee.emp_DepId">
<option *ngFor="let depName of getDepartments(); let i = index" [value] = "getDepId(depName)">
{{depName}}
</option>
</select>
But ideally it should be like this :
// output of getDepartments() should look like this
[
{ id : 1 , name : 'department 1'},
{ id : 2 , name : 'department 2'}
{ id : 3 , name : 'department 3'}
]
<select class="form-control" name="emp_DepId" [(ngModel)]="employee.emp_DepId">
<option *ngFor="let dep of getDepartments(); let i = index" [value] = "dep.id">
{{dep.name}}
</option>
</select>

How to set the object value in ng-model, in select tag, from an object array. and is there an easy way to add filters on ng-options,

Here is my html :
<body ng-controller="myCtrl">
{{loadDataSubject('${subjectList}')}}
{{loadDataTopic('${topicList}')}}
<h1 class = "bg-success" style="color: red;text-align: center">Fill in the below details for Question Template : -</h1> <br>
<div class="container">
<form method="get" action="createTemplate">
<div class="form-group">
<label for="sel1">Topics (select one):</label>
<select class="form-control" ng-model="selectedTopic" ng-options="topic.name as topic.name for topic in topics">
</select> <br>
{{selectedTopic}}
<label for="sel1">Subject (select one):</label>
<select name="subject" value= "" class="form-control" ng-model ="selectedSubject" ng-options="sub.name as sub.name for sub in subjects">
</select> <br>
<label for="sel1">Negative marking:</label>
<select class="form-control" name="negativeMarks">
<option>Yes</option>
<option>No</option>
</select> <br>
<label>Reference Book:</label>
<input type="text" class="form-control" name="ref" required>
<label for="sel1">Number of Questions:</label>
<input type="number" class="form-control" name="questionCount" required><br>
<input class ="bg-primary" type="submit" value="submit and download template">
</div>
</form>
</div>
</body>
and here is the script :
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.subjects = [];
$scope.topics = [];
$scope.selectedSubject = {};
$scope.selectedTopic = {};
$scope.loadDataSubject = function(subjectList) {
$scope.subjects = JSON.parse(subjectList);
};
$scope.loadDataTopic = function(topicList) {
$scope.topics = JSON.parse(topicList);
};
});
I want to add a filter to options to selectonly the subjects of selected Topic,
something like filter : selectedTopic.id
Error is
angular.js:38 Uncaught Error: [$rootScope:infdig] http://errors.angularjs.org/1.4.8/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…turn%20b(f%2Cc%2Ce)%7D%22%2C%22newVal%22%3A74%2C%22oldVal%22%3A68%7D%5D%5D
at angular.js:38
at r.$digest (angular.js:15934)
at r.$apply (angular.js:16160)
at angular.js:1679
at Object.e [as invoke] (angular.js:4523)
at c (angular.js:1677)
at yc (angular.js:1697)
at Zd (angular.js:1591)
at angular.js:29013
at HTMLDocument.b (angular.js:3057)
before that i want to bind the value of object to ng-model, while the objects name gets binded. Please help me, I'm new with this.
subjects:
[{"subjectId":1,"name":"ComputerScience","code":"CS"},{"subjectId":2,"name":"Computer Basics","code":"CS","documentUrl":"None"},{"subjectId":3,"name":"Computer Basics","code":"CS","documentUrl":"None"},{"subjectId":4,"name":"php","code":"PHP01","documentUrl":"None"},{"subjectId":5,"name":"JAVA","code":"JAVA01","childSubjects":[{"subjectId":6,"name":"Core Java","code":"JAVA02","parentSubject":5,"childSubjects":[{"subjectId":8,"name":"Thread","code":"JAVA04","parentSubject":6},{"subjectId":9,"name":"Object Class","code":"JAVA05","parentSubject":6},{"subjectId":10,"name":"Inheritance","code":"JAVA06","parentSubject":6}]},{"subjectId":7,"name":"Advance Java","code":"JAVA03","parentSubject":5,"childSubjects":[{"subjectId":11,"name":"Servlet","code":"JAVA07","parentSubject":7}]}]},{"subjectId":12,"name":"Computer Basics","code":"CS","documentUrl":"None"}]
topics:
[{"topicId":1,"name":"Technical","code":"TECH","isSubjectsRelated":1,"description":"All Technical subjects","isActive":1,"subjects":[{"subjectId":1,"name":"ComputerScience","code":"CS"},{"subjectId":1,"name":"ComputerScience","code":"CS"}]},{"topicId":2,"name":"GATE","code":"GATE","isSubjectsRelated":1,"description":"GATE exam","isActive":1,"subjects":[]},{"topicId":5,"name":"Programming","code":"PROG","isSubjectsRelated":0,"description":"Coding skills","isActive":1,"subjects":[{"subjectId":5,"name":"JAVA","code":"JAVA01"}]}]
Change your Topics select-box to this
<label for="sel1">Topics (select one):</label>
<select class="form-control" ng-model="selectedTopic" ng-options="topic as topic.name for topic in topics">
</select>
And similarly for subject selectbox.Check out this plunker.

How to enable disable a select drop down list using radio buttons with angularjs?

I have been searching all over for the internet looking on how to enable or disable this drop down list using radio buttons specifically when the radio button value is equal to prof the drop down list should be disabled, but with no help. I did come up with an example but didn't work. Any help would be appreciated.
registration.html
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label">Qualification</label>
<div class="col-lg-10 col-md-9">
<div class="radio-custom radio-inline">
<input type="radio" ng-model="QualificationDetails.qualification_type" value="edu" name="radio1" id="radio4">
<label for="radio4">Educational</label>
</div>
<div class="radio-custom radio-inline">
<input type="radio" ng-model="QualificationDetails.qualification_type" value="prof" name="radio1" id="radio5">
<label for="radio5">professional</label>
</div>
</div>
</div>
//This is the drop down that I need to diable
<div class="form-group">
<label class="col-sm-2 control-label" for="Qulitype">Qualification type</label>
<div class="col-sm-10">
<select name="repeatSelect" id="repeatSelect" ng-disabled="QualificationDetails.qualification_type == 'prof'" ng-model="QualificationDetails.qualification" class="form-control">
<option ng-repeat="quali in qualiLevel" value="{{quali.qualification_id}}">{{quali.quali_level}}</option>
</select>
</div>
</div>
This is the code I implemented to work above scenario. But didn't work :(
regController.js
$scope.$watch('QualificationDetails.qualicication_type', function (QualiType) {
if (angular.isUndefined($scope.QualificationDetails)) {
return;
}
if (QualiType === 'prof') {
$scope.QualificationDetails.qualification_type = $scope.QualiType;
}
else {
if ($scope.QualificationDetails.qualification_type !== null) {
$scope.QualiType = $scope.QualificationDetails.qualification_type;
$scope.QualificationDetails.qualification_type = null;
}
}
});
the above scenario is that when it comes to qualifications if qualification type is equal to professional (prof) drop down list is disabled and when it is educational the drop down list should be enabled. Any idea on how to achieve this.
This is the Quality level json. I get it through the qualitylevel.service.
(function initController() {
deptService.getdepts(function (res) {
$scope.depts = JSON.parse(res.data);
});
qualiService.getquali(function (res) {
console.log("inside ");
$scope.qualiLevel = JSON.parse(res.data);
});
console.log("inside service");
})();
It seems to me, that your code works fine without watcher you have added. I hope I understood what you want correctly. Try this snippet:
angular
.module('app', [])
.controller('Ctrl', function($scope) {
$scope.qualiLevel = [
{quali_level: 'A', qualification_id: 1},
{quali_level: 'B', qualification_id: 2}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="Ctrl">
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label">Qualification</label>
<div class="col-lg-10 col-md-9">
<div class="radio-custom radio-inline">
<input type="radio" ng-model="QualificationDetails.qualification_type" value="edu" name="radio1" id="radio4">
<label for="radio4">Educational</label>
</div>
<div class="radio-custom radio-inline">
<input type="radio" ng-model="QualificationDetails.qualification_type" value="prof" name="radio1" id="radio5">
<label for="radio5">professional</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="Qulitype">Qualification type</label>
<div class="col-sm-10">
<select name="repeatSelect" id="repeatSelect" ng-disabled="QualificationDetails.qualification_type == 'prof'" ng-model="QualificationDetails.qualification" class="form-control">
<option ng-repeat="quali in qualiLevel" value="{{quali.qualification_id}}">{{quali.quali_level}}</option>
</select>
</div>
</div>
</div>
</div>
As the control is radiobutton, your QualificationDetails.qualification_type value will be set to 1 or 0 and not to the label value. You have to have different variables for two radio buttons. Based on their value you have to set QualificationDetails.qualification_type = 'prof' or something
You can also try $parent.QualificationDetails.qualification_type instead as answered in How can I get the value of the checked radio button when submitting a form using angularjs?
Thanks everyone for helping me out. Just felt wanted to show I implemented it correctly and other programmers to increase their knowledge. Using $watch to temporaly hide the drop down list details).
the registrationController.js
$scope.$watch('QualificationDetails.qualification_type', function (Val) {
if (angular.isUndefined($scope.QualificationDetails))
return;
if (Val !== 'prof') {
$scope.QualificationDetails.qualification = $scope.tempValue;
}
else {
if ($scope.QualificationDetails.qualification !== null) {
$scope.tempValue = $scope.QualificationDetails.qualification;
$scope.QualificationDetails.qualification = null;
}
}
});
Implemented through this example.

How to hide field and use ng-model for Rest Service?

I have field that i want to hide permanently from the view but i want to use ng-model for Rest Service to do some calculation for other fields. How to achieve that task using AngularJS ?
So far tried code...
main.html
<div class="form-group col-md-6" ng-disabled="disableEffComp" ng-hide="true">
<div>
<label class="control-label" for="controlEffect">Overall
Control Effectiveness Computed</label>
</div>
<select kendo-drop-down-list k-data-value-field="'id'"
k-data-text-field="'text'" k-option-label="'Select'"
k-data-source="ctrlEffOptions"
ng-model-options="{ updateOn: 'blur' }"
ng-model="processRating.controlEffectivenessRatingComputeKey"
readOnly="compReadOnly" id="controlEffect">
</select>
</div>
mainCtrl.js
$scope.overrideBusinessDec = function () {
if ($scope.processRating.controlEffectivenessRatingComputeKey && $scope.processRating.controlEffectivenessRatingOverrideKey !== $scope.processRating.controlEffectivenessRatingComputeKey) {
Rating.getProcessRatingFields($scope.processRating.controlEffectivenessRatingOverrideKey, $scope.processRating.finalOutcomeInherentRiskRatingKey).then(function (response) {
$scope.processRating.residualRiskRatingComputeKey = response.data.residualRiskRatingComputeKey;
$scope.processRating.residualRiskRatingOverrideKey = response.data.residualRiskRatingComputeKey;
$scope.riskBusinessOptions = response.data.residualRiskOverride;
});
}
};

Categories