angular validation not working on select - javascript

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.

Related

How to Pass id and name from the first form, and Show only the name in second form in angularjs

I Have two forms.In these forms am getting input from the first form and show that in the second form, Which means if the user selected the currency from the dropdown, i need to pass id and the the currency name. But show only the currency name in the second form. I tried one method (dont know whether it is correct or not) it is showing the id only. am new to angular. is there anyway to solve this?
HTML
<div class="row text-center" ng-show="firstform">
<form name="validation">
<label>Currency</label>
<select ng-model="CurrencyId" ng-selected="CurrencyId" class="form-control" id="CurrencyId">
<option ng:repeat="CurrencyId in currencyList" ng-selected="selectedCurrencyType == CurrencyId.id" value={{CurrencyId.currencyId}}>{{CurrencyId.name}}</option>
</select>
<label>Grade</label>
<select ng-model="GradeId" ng-selected="GradeId" class="form-control" id="GradeId">
<option ng:repeat="GradeId in RaceGradeList" ng-selected="selectedGrade == GradeId.id" value={{GradeId.id}}>{{GradeId.gradeName}}</option>
</select>
<button type="submit"value="add" ng-click="savedetails()" />
</form>
</div>
<div class="row text-center" ng-show="secondform">
<form name="thirdform">
<ul >
<li><p>Currency:{{CurrencyId}}</p> </li>
<li><p>Grade:{{GradeId}}</p> </li>
</ul>
</form>
</div>
angular controller
$scope.savedetails = function () {
$scope.firstform= false;
$scope.secondform = true;
}
This is the most simplest solution that you can go for. Instead of having the value={{CurrencyId.currencyId}} set it as value={{CurrencyId.name}} for the options in the dropdown and you are good to go. Below is the demo for the same. But if you want to save currencyId as the value then you will have to iterate over the array and find the name based on the selected currencyId and then show that in the view.
UPDATE
Updated the code to have the currencyId being stored as the selected value and then based on that showing the name in the view.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.currencyList = [{
currencyId: 1,
name: "INR"
},
{
currencyId: 2,
name: "$"
},
{
currencyId: 3,
name: "#"
}
];
$scope.currencyChanged = function() {
var selectedCurrency;
for (var i = 0; i < $scope.currencyList.length; i++) {
var thisCurr = $scope.currencyList[i];
if ($scope.CurrencyId == thisCurr.currencyId)
selectedCurrency = thisCurr.name;
}
return selectedCurrency;
}
$scope.firstform = true;
$scope.savedetails = function() {
$scope.firstform = false;
$scope.secondform = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div class="row text-center" ng-show="firstform">
<form name="validation">
<label>Currency</label>
<select ng-model="CurrencyId" ng-selected="CurrencyId" class="form-control" id="CurrencyId">
<option ng:repeat="CurrencyId in currencyList" ng-selected="CurrencyId == CurrencyId.currencyId" value={{CurrencyId.currencyId}}>{{CurrencyId.name}}</option>
</select>
<button type="button" value="add" ng-click="savedetails()">Save Details</button>
</form>
</div>
<div class="row text-center" ng-show="secondform">
<form name="thirdform">
<ul>
<li>
<p>Currency:{{currencyChanged()}}</p>
</li>
</ul>
</form>
</div>
</body>
Hope it helps :)
You can use ng-options , its very flexiable where we can display one value and select either entire object or any specific property.
Please check below plunker , hope it meets your requirement
https://plnkr.co/edit/JQjmAwk62R8rfAlTZ696?p=preview
<select ng-model="CurrencyId" ng-options="currency.id for currency in currencyList" class="form-control" id="CurrencyId" >
</select>
For more details on ng-options , go through below video
https://www.youtube.com/watch?v=vqx3zCy4d3I
try
<li><p>Currency:{{CurrencyId.name}</p> </li>

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/

how to display selected value of dropdown in input text fields in angular js

html file:
<select ng-model="shipping" ng-options="shipping.shipping for shipping in shipAddress">
<option value=''>--Select Address --</option>
</select>
<form name="shippingForm" class="form-horizontal" role="form">
<div class="form-group">
<p class="control-p col-sm-2" for="Address">Address Line1</p>
<div class="col-sm-10">
<input type="text" name="Address" placeholder="Address Line1"
ng-model="shipping.addressLine1" class="input-width" ng-init ="shipping.addressLine1"/>
</div>
</div>
<div class="form-group">
<p class="control-p col-sm-2" for="Address2">Address Line2:</p>
<div class="col-sm-10">
<input type="text" name="AddressLine" placeholder="Address Line2" ng-model="shipping.addressLine2" class="input-width" />
</div>
</div>
</form>
js file:
if (data){
console.log(data);
$scope.addressToShip = data;
var ShipAddress=[];
storeLocally.set('ship Info', data);
if(data.addressLine2 == null){
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1
};
});
}
else{
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1 +', '+ address.addressLine2
};
});
}
}
},
function (data) {
//if (data.status == 500) {
// $scope.addressError = "Oops! No Address Found!";
};
data:
{0 :"123 waller st,suite#220"},
{1 :"323 waller st,suite#230"}
The problem is the form I am using intially to save data. Once data is saved to db it is coming in dropdown. After choosing one value from dropdown it should come to text fields.
I have tried so far ng-model by using same variable names,even though form's ng-model and dropdown's ng-model have same variable i.e. shipping.. But it didn't work. Please help me out what I am missing in here.
If I understand your goal and you data's schema, you need to change the ng-model of the input[name="Address"] to shipping.addressLine1.shipping.
I get this idea according the data's structure that came from the .map:
return {
shipping: address.addressLine1
};
You can see the structure when you pick a option from the select - the model will displayd and you can see that the structure is (for example):
{
"addressLine1": {
"shipping": "123 waller st"
}
}
If you have a question about this, let me know.
I tried to simulate the situation without the server, hopefully I simulate it right.
Now, to the code:
angular.module('myApp', []).
controller('ctrl', function($scope) {
var data = [{
addressLine1:"123 waller st", addressLine2:"suite#220"
}];
if (data) {
console.log(data);
$scope.addressToShip = data;
var ShipAddress = [];
//storeLocally.set('ship Info', data);
if (data.addressLine2 == null) {
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1
};
});
}
else {
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1 +', '+ address.addressLine2
};
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
<select ng-model="shipping.addressLine1" ng-options="shipping.shipping for shipping in shipAddress">
<option value=''>--Select Address --</option>
</select>
<br />
<pre>
{{shipping | json}}<br />
{{shipping.addressLine1 | json}}
</pre>
<form name="shippingForm" class="form-horizontal" role="form">
<div class="form-group">
<p class="control-p col-sm-2" for="Address">Address Line1</p>
<div class="col-sm-10">
<input type="text" name="Address" placeholder="Address Line1"
ng-model="shipping.addressLine1.shipping" class="input-width" ng-init ="shipping.addressLine1"/>
</div>
</div>
<div class="form-group">
<p class="control-p col-sm-2" for="Address2">Address Line2:</p>
<div class="col-sm-10">
<input type="text" name="AddressLine" placeholder="Address Line2" ng-model="shipping.addressLine2" class="input-width" />
</div>
</div>
</form>
</div>
Did you try using AngularJS' ng-change attribute in the drop down?
Try like this:
<select ng-model="shipping" ng-options="shipping.shipping for shipping in shipAddress" ng-change="someFunction(shipping.shipping)">
<option value=''>--Select Address--</option>
</select>
In your controller add the following function:
$scope.someFunction = function(shipping) {
$scope.shipping.addressLine1 = // Assign value from the shipping variable here
$scope.shipping.addressLine2 = // Assign value from the shipping variable here
}
Hope this helps!
Here is a working jsFiddle https://jsfiddle.net/ashishU/umn8or3g/1/

Getting data from the server and using ng-options in select control is failing to show options

this my HTML
<div ng-app="timeTable" ng-controller="addCoursesCtrl">
<button class="btn btn-primary" ng-click="addNewCourse()">Add New Course</button><br/><br/>
<fieldset ng-repeat="choice in choices">
<div class="row">
<div class="col-md-6">
<select class="form-control" ng-model="choice.type" ng-options="s for s in coursetoAdd">
<option value="{{s.shortCut}}">{{s.name}}</option>
</select>
</div>
<div class="col-md-6">
<input type="text" placeholder="Enter Course Name" name="" class="form-control" ng-model="choice.course"/>
</div>
</div>
<br/>
</fieldset>
<button class="btn btn-primary" ng-click="convertAndSend()">Submit</button>
</div>
this the js
var timeTable = angular.module("timeTable",[]);
timeTable.controller("addCoursesCtrl", function ($scope,$http) {
$scope.choices = [{ course: '', type: '' }];
$scope.coursetoAdd ;
$http.get("/Semster/getSuggtedCourses").then(function (response) {
$scope.coursetoAdd = response.data;
});
$scope.addNewCourse = function () {
var newITemNo = $scope.choices.length + 1;
$scope.choices.push({ course: '', type: '' });
};
$scope.convertAndSend = function () {
var asJson = angular.toJson($scope.choices);
console.log(asJson);
$http.post('/Semster/Add', asJson);
};
});
this code bind an object {"course":...,"type":....} every time you click on add course ,and add input field dynamically , my problem is with select control,I'm getting the data from server and use it with ng-optin ,but all it shows it's just [object Object] in select option not the real value.
Assuming that the data returned from getSuggestedCourses is an array of objects, the ng-options selector:
s for s in courseToAdd
will bind s to each object in the array. You need to bind to the fields in the object like this
s.value as s.name for s in courseToAdd

AngularJS binding checkboxes to model property

I have an AngularJS app with a list of users with an 'Edit' button beside each user. Each user has a number of subjects associated with them. When I click on 'Edit', it opens a form in which you can edit user details, and select associated subjects from a list of checkboxes. I'm trying to figure out how to bind the subject checkboxes so that the subjects which the
user is already associated with are checked, and the rest are unchecked. Any suggestions appreciated.
My HTML:
<form name="UserEditForm">
Name: <br /> <input type="text" name="name" ng-model="user.name"> <br />
{{name}}
Email: <br /> <input type="text" name="name" ng-model="user.email"> <br />
{{email}}
<div class="control-group">
<label class="control-label" for="inputSubjects">Subjects:</label>
<div class="form-group">
<label ng-repeat="subject in subjects" class="checkbox">
<input type="checkbox" ng-checked="{user.subjects}" name="selectedSubjects[]" value="{{subject.id}}" ng-model="subject.selected"> {{subject.name}}
</label>
</div>
<br />
<a ng-click="updateUser()" class="btn btn-small btn-primary">Save Changes</a>
</form>
My UserEditCtrl:
angular.module('myApp.controllers')
.controller('UserEditCtrl', ['$scope', '$routeParams','SubjectsFactory', 'UserFactory', '$location',
function ($scope, $routeParams, SubjectsFactory, UserFactory, $location) {
// callback for ng-click 'updateUser':
$scope.updateUser = function () {
$scope.user.subjects = $scope.selection;
UserFactory.update($scope.user);
$location.path('/users');
};
// callback for ng-click 'cancel':
$scope.cancel = function () {
$location.path('/users');
};
$scope.user = UserFactory.show({id: $routeParams.userid});
$scope.subjects = SubjectsFactory.query();
$scope.selection = [];
// helper method
$scope.selectedSubjects = function selectedSubjects() {
return filterFilter($scope.subjects, { selected: true });
};
// watch subjects for changes
$scope.$watch('subjects|filter:{selected:true}', function (nv) {
$scope.selection = nv.map(function (subject) {
return subject.id;
});
}, true);
}]);
As #jkinkead said, your code looks good, I fixed the ng-checked binding in accordance with your ng-model expression
Here's a simplified plunker : http://plnkr.co/edit/qaIBExtVbNdSXlQlbMym?p=preview
EDIT 1: I edited and improved the plunker to get closer to your case.

Categories