AngularJS - Ng-change updating value but not toggling radio button - angularjs

I have two input options that are linked via ng-model in order to display always the same country in both places.
<select ng-model="selectedCountry" ng-options="country.name for country in countries">
<select ng-model="selectedCountry" ng-options="country.name for country in countries">
Each country has different shipping costs, and once the country is selected you can also choose between different shipping options ("normal" and "express" with a radio button. I want to make it always display the "normal" cost when switching the country, and I made it by adding a ng-click to each of the input options and adding a ng-change in order to listen to the changes:
<select ng-model="selectedCountry" ng-options="country.name for country in countries" ng-change="changeShipping()" ng-click="shippingPrice=selectedCountry.shipping.normal">
The problem is that while the data shown in the view is the correct when changing the country, but the radio button is still set in the wrong option.
This is my controller logic:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.countries = [{
"name": "Freedonia",
"shipping" :
{
"normal":30,
"express":70
}
},{
"name": "Mordor",
"shipping" :
{
"normal":70,
"express":110
}
},{
"name": "Oz",
"shipping" :
{
"normal":140,
"express":180
}
}];
$scope.selectedCountry = $scope.countries[0];
$scope.changeShipping = function() {
return $scope.shippingPrice = $scope.selectedCountry.shipping.normal;
};
});
You can see a working fiddle here Thanks in advance!

Use ng-model with input[radio] and set it's value on select change.
UPDATED JSFIDDLE
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.shippingType = 'normal'; // initial value for input[radio]
$scope.countries = [{
"name": "Freedonia",
"shipping": {
"normal": 30,
"express": 70
}
}, {
"name": "Mordor",
"shipping": {
"normal": 70,
"express": 110
}
}, {
"name": "Oz",
"shipping": {
"normal": 140,
"express": 180
}
}];
$scope.selectedCountry = $scope.countries[0];
$scope.changeShipping = function () {
$scope.shippingType = 'normal'; // set back to normal on country change
return $scope.shippingPrice = $scope.selectedCountry.shipping.normal;
};
});
.summary{
background-color:gray;
border:1px solid black;
font-family:Arial;
margin-bottom:52px;
color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="myCtrl" ng-app="myApp">
<div class="summary">
Summary:<br>
Country:<select ng-model="selectedCountry" ng-options="country.name for country in countries" ng-change="changeShipping()">
</select><br>
Shipping Costs:
{{selectedCountry.shipping[shippingType]}}
</div>
<div>
<select ng-model="selectedCountry" ng-options="country.name for country in countries" ng-change="changeShipping()">
</select>
</div>
Shipping costs:
<form>
<input type="radio" name="shippingOptions" value="normal" ng-model="shippingType">
Normal {{selectedCountry.shipping.normal}}<br>
<input type="radio" name="shippingOptions" value="express" ng-model="shippingType">
Express {{selectedCountry.shipping.express}}<br>
</form>
</div>

Related

eHow to create drop down (grouped) using ng-options?

I have json of all countries with me.
{"countries":[
{"name":"Afghanistan","code":"AF"},
{"name":"Åland Islands","code":"AX"},
{"name":"United States","code":"US"},
{"name":"Canada","code":"CA"},
{"name":"India","code":"IN"}
]};
I want to create drop down like
"
Choose Country(Default)
United States
Canada
------------
Åland Islands
Afghanistan
India
So on..."
I can be achieved via ng-repeat like
<select name="country" id="country" data-ng-model="country" required data-ng-change="allSelect()">
<option value="default" data-ng-data-ng-bind="'Choose Country'"></option>
<option value="{{cList.code}}" data-ng-if="cList.code === 'US'" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
<option value="{{cList.code}}" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
<option value="default1">--------------------------------------------------</option>
<option value="{{cList.code}}" data-ng-if="cList.code !== 'US' && cList.code !== 'CA'" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
</select>
How can i do same via ng-options?
Currently if i want to select any option by default is not happening its creating blank string.
Country list and default values i am getting from different ajax call.
You need to make some changes to your JSON
JSON
{
"Collections": [{
"Name": "North America",
"Countries": [{
"Name": "United States",
"code": "US"
}, {
"Name": "Canada",
"code": "CA"
}
]
}, {
"Name": "Asia",
"Countries": [{
"Name": "India",
"value": "IN"
}
]
}]
}
HTML
<body ng-controller="dobController">
<div class="col-md-20">
<div id="main">
<form class="form-horizontal" role="form">
<label class="control-label col-md-2">Filter List:</label>
<div class="col-md-5">
<select ng-model='theModel' ng-change="display(theModel)">
<optgroup ng-repeat='group in collection' label="{{group.Name}}">
<option ng-repeat='veh in group.Countries' value='{{group.Name}}::{{veh.Name}}'>{{veh.Name}}</option>
</optgroup>
</select>
</div>
</form>
</div>
</div>
Controller
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope", "$http",
function($scope, $http) {
$http.get('test.json').then(function(response) {
$scope.collection = response.data.Collections;
console.log(response);
});
$scope.display = function(name) {
alert(name.split("::")[0] + "." + name.split("::")[1]);
}
}
]);
DEMO

how to make drop-down list dependent using json?

Im trying to create a dependent drop-down list box using json.For example: if the car brand selected is "bmw" then the car model drop-down must display only "suv" from the list and other two options shouldn't be displayed.Likewise for "Mercedes" it should display only "suv" and "coupe" in the car model. And also please explain what is the use of json? also how it effect the code.
my.html
Car Brand:
<select name="carname" ng-model="userSelect" required>
<option value="">--Select--</option>
<span ng-show="valdate.carname.$error.required">Car name</span>
<option ng-repeat="ManufactureBrand in a" ng-bind="ManufactureBrand" >
{{ManufactureBrand}}
</option>
</select>
<br/>
<br/> Car Model:
<select name="carmodel" ng-model="selectCar" required>
<option value="">--Select--</option>
<span ng-show="valdate.carmodel.$error.required">Car name</span>
<option ng-repeat="CarName in b" ng-bind="CarName">
{{CarName}}
</option>
</select>
<br/>
<input type="submit" ng-click="checkselection()" ng-disabled="valdate.carname.$invalid && valdate.carmodel.$invalid">
script.js
app.factory('Brandtest', function () {
var brand = {};
brand.sample = ['Bmw', 'Mercedes', 'Honda'];
brand.car = ['Suv', 'Sedan', 'Cope'];
{
return brand;
}
});
app.controller('selectDropdown', ['$scope', 'Brandtest', function ($scope, Brandtest) {
$scope.a = Brandtest.sample;
$scope.b = Brandtest.car;
$scope.list=[];
$scope.carlist=[];
$scope.checkselection = function () {
if ($scope.userSelect != "" && $scope.userSelect != undefined &&
$scope.selectCar != "" && $scope.selectCar != undefined )
{
$scope.list.push($scope.userSelect);
$scope.carlist.push($scope.selectCar);
}
Thanks in advance.
Here is the working plunkr
You have to modified you code as below
your factory should be like this
app.factory('Brandtest', function () {
var brand = {};
brand.sample =[
{
"id": 0,
"carName": "BMW"
},
{
"id": 1,
"carName": "Mercedes"
},
{
"id": 2,
"carName": "Honda"
}
];
brand.car =[
{
"id": 0,
"carType": "Suv",
"parentId": 0
},
{
"id": 1,
"carType": "Sedan",
"parentId": 1
},
{
"id": 2,
"carType": "Cope",
"parentId": 2
}
];
{
return brand;
}
});
In your HTML modify the code like below
<body ng-controller="selectDropdown">
Car Brand:
<select name="carname" ng-model="userSelect" ng-options="p.carName for p in a" required>
<option value="">--Select--</option>
<span ng-show="valdate.carname.$error.required">Car name</span>
</select>
<br/>
<br/> Car Model:
<select name="carmodel" ng-model="selectCar" ng-options="c.carType for c in b | filter:{parentId: userSelect.id}" required>
<option value="">--Select--</option>
<span ng-show="valdate.carmodel.$error.required">Car name</span>
</select>
<br/>
<input type="submit" ng-click="checkselection()" ng-disabled="valdate.carname.$invalid && valdate.carmodel.$invalid">
<table>
<tr>
<th>Car Name</th>
<th>Car Model</th></tr>
<tr ng-repeat="carz in list track by $index">
<td>{{carz.carName}}</td>
<td>{{carlist[$index].carType}}</td>
</tr>
</table>
</body>
You have to maintain some co-relation between the 2 dropdowns. Better would be to have a single json object and use ng-options for populating the second dropdown based on value selected in first dropdown. Run the demo program below and you will get the point.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>Select a car:</h1>
<select ng-model="x" ng-options="x for (x, y) in cars"></select>
<h1 ng-if="x">Category: </h1>
<select ng-if="x" ng-model="y" ng-options="y for y in x"></select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.cars = {
"car01" : ["Ford", "BMW", "NISSAN"],
"car02" : ["Fiat", "Infinity"],
"car03" : ["Volvo", "Toyota"]
}
});
</script>
</body>
</html>

Dynamic dropdown select in AngularJS not working

I am practicing with Angular and want to give users the option to choose from 3 dropdown select menus. The third menu should be dynamic depending on the selection from the previous two menus.
My html:
// First dropdown menu, static
<select ng-model="selectedLetter" ng-change="setColorSelection()"
ng-options="letter as letter for letter in letters">
</select>
<br>
// second dropdown menu, static
<select ng-model="selectedNumber" ng-change="setColorSelection()"
ng-options="number as number for number in numbers">
</select>
<br>
// third dropdown menu, should be dynamic
<select ng-model="selectedColor"
ng-options="color as color for color in colorSelection">
</select>
In my controller, I have the lists like this
$scope.letters = ['A', 'B'];
$scope.numbers = ['1', '2'];
var colors = {
'A1': [{"red": "100"}, {"pink": "101"}],
'A2': [{"blue": "202"}, {"black": "203"}],
'B1': [{"yellow": "304"}, {"orange": "305"}],
'B2': [{"white": "406"}, {"black": "407"}]
};
$scope.colorSelection = [];
$scope.setColorSelection = function() {
if ($scope.selectedLetter && $scope.selectedNumber) {
$scope.colorSelection = colors[$scope.selectedLetter + $scope.selectedNumber];
console.log($scope.colorSelection);
}
}
So if the user selects 'A' from the first menu and '2' from the second menu, he should see the options for 'A2' in the third menu.
Problem: currently, the third menu is not populating.
When I do console.log($scope.colorSelection), I get [Object, Object] in the console instead of [{"blue": "202"}, {"black": "203"}].
Also, I only want to display the colors in the menu, not the numbers associated with them. I was able to do this in ng-repeat using (key, value), not sure how I would do this in ng-options.
Change your color object like
var colors = {
'A1': [{"color": "Red", "code": "100"}, {"color":"pink", "code": "101"}]
};
and ng-option
<select ng-model="selectedColor"
ng-options="color.code as color.color for color in colorSelection">
</select>
Dropdown working properly and correctly. The problem in your json object [{"red": "100"}, {"pink": "101"}].
Dropdown can be used as the source object, or an array.
All possible options dropdown use, see the documentation.
I think there are two ways to change your json:
Transform it into an array of objects.
Transform it into a single object with the keys.
First way:
var colors = {
'A1': [{"color": "red", "code": "100"}, {"color":"pink", "code": "101"}]
};
Second way:
var colors = {
'A1': {"red": "100","pink": "101"}
};
See example on jsfiddle;
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.letters = ['A', 'B'];
$scope.numbers = ['1', '2'];
var colorsByArray = {
'A1': [{
"color": "red",
"code": "100"
}, {
"color": "pink",
"code": "101"
}]
};
var colorsByObject = {
'A1': {
"red": "100",
"pink": "101"
}
};
$scope.colorSelection = [];
$scope.setColorSelection = function() {
if ($scope.selectedLetter && $scope.selectedNumber) {
$scope.colorSelectionByArray = colorsByArray[$scope.selectedLetter + $scope.selectedNumber];
$scope.colorSelectionByObject = colorsByObject[$scope.selectedLetter + $scope.selectedNumber];
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
Choose 'A'
<select ng-model="selectedLetter" ng-change="setColorSelection()" ng-options="letter as letter for letter in letters">
</select>
<br>Choose '1'
<select ng-model="selectedNumber" ng-change="setColorSelection()" ng-options="number as number for number in numbers">
</select>
<br>
<h3>
IterateByArray
</h3>
<select ng-model="selectedColor" ng-options="color.code as color.color for color in colorSelectionByArray">
</select>
<h3>
IterateByObject
</h3>
<select ng-model="selectedColor" ng-options="v as k for (k, v) in colorSelectionByObject">
</select>
</div>
</div>

Reset Model Value On Cascaded DropDown Change

I have two drop downs .One to show departments and other to show sections on change of department .
<div class="row" ng-controller="cascaded as cas">
<div class="form-group">
<label for="select-department" class="control-label col-md-2">Department</label>
<div class="col-md-4">
<select id="select-department" class="form-control" name="department" ng-model="myModel.department"
ng-options="option.name for option in departments track by option.id">
<option value=""></option>
</select>
</div>
<label for="select-department" class="control-label col-md-2">Section</label>
<div class="col-md-4">
<select id="select-section" class="form-control" name="section" ng-model="myModel.section"
ng-options="option.name for option in sections track by option.id">
<option value=""></option>
</select>
{{myModel.section}}
</div>
</div>
</div>
It works fine for me . If I change department all respective section gets updated and if I select any section respective section also gets assigned to the model . But the problem is if second time I change my department value, section drop down gets updated the model value doesn't reset to blank . It still shows the last selected value .
var app = angular.module("mainApp", []);
angular.module("mainApp").controller("cascaded", function ($scope, $filter) {
$scope.departments = [
{
id: 1, name: "Dep A"
}, {
id: 2, name: "Dep B"
}, {
id: 3, name: "Dep C"
}];
var sections = [
{
id: 1, name: "Sec A", parentId: 1
}, {
id: 2, name: "Sec B", parentId: 2
}, {
id: 3, name: "Sec C", parentId: 3
}];
$scope.$watch("myModel.department", function (newVal) {
if (newVal) {
$scope.sections = $filter("filter")(sections, { parentId: newVal.id });
}
});
})
I want to reset my model value when section drop down gets refreshed with new data .
You need to assign the sections value to your mymodel.section value
$scope.myModel.section= $scope.sections;
Because $scope.myModel.section is does not update, when you changing the department,
Your watch event should be
$scope.$watch("myModel.department", function (newVal) {
if (newVal) {
$scope.sections = $filter("filter")(sections, { parentId: newVal.id });
**$scope.myModel.section= $scope.sections;**
}
});
Fiddler Demo
Simply put one method in ng-change of department like:
<select id="select-department" class="form-control" name="department" ng-model="myModel.department"
ng-options="option.name for option in departments track by option.id" ng-change="setBlank()">
<option value=""></option>
</select>
And in the method setBlank() set myModel.section to blank like this:
$scope.setBlank=function(){
$scope.myModel.section='';
}

AngularJs Select Not Updating When Model Updated

I'm trying to programmatically update the selected item from my controller and it's not working. When I click the submit button, all it does is clear out the select. What I expect is that the second option (Perth) gets selected.
Look at this plunker for more info. http://jsfiddle.net/ky5F4/
Thanks
<div ng-controller="MyController" ng-app>
<div>Number of datasets= {{datasets.length}}</div>
<div>
<select class="dataset" size="1" ng-model="selectedDataset">
<option ng:repeat="dataset in datasets" value="{{dataset.name}}">
<h3>{{dataset.name}}</h3>
</option>
</div>
<input type="button" value="submit" ng-click="Select()"></input>
</div>
function MyController($scope) {
$scope.datasets = [{
id: 'id-1',
name: 'Brisbane'
}, {
id: 'id-2',
name: 'Perth'
}, {
id: 'id-3',
name: 'Melbourne'
}];
$scope.selectedDataset = 'id-1';
$scope.Select = function () {
alert('testing');
$scope.selectedDataset = 'id-2';
}
}
Use ng-options instead of ng-repeat.
<select class="dataset" size="1" ng-model="selectedDataset"
ng-options="dataset.id as dataset.name for dataset in datasets">
Working fiddle
You can see the docs here

Resources