Setting selected values for ng-options bound select elements - angularjs

Fiddle with the relevant code: http://jsfiddle.net/gFCzV/7/
I'm trying to set the selected value of a drop down that is bound to a child collection of an object referenced in an ng-repeat. I don't know how to set the selected option since I can't reference the collection it's being bound to in any way that I'm aware of.
HTML:
<div ng-app="myApp" ng-controller="SomeController">
<div ng-repeat="Person in People">
<div class="listheader">{{Person.firstName}} {{Person.lastName}}</div>
<div class="listitem" ng-repeat="Choice in Person.Choices">
{{Choice.Name}}:
<select
ng-model="Choice.SelectedOption"
ng-options="choice.Name for choice in Choice.Options"></select>
{{Choice.SelectedOption.ID}}
</div>
</div>
</div>
JS:
var myApp = angular.module('myApp', []);
myApp.controller("SomeController", function($scope) {
$scope.People = [{
"firstName": "John",
"lastName": "Doe",
"Choices": [
{
"Name":"Dinner",
"Options":[{Name:"Fish",ID:1}, {Name:"Chicken",ID:2}, {Name:"Beef",ID:3}],
"SelectedOption":{Name:"Chicken",ID:2} //this doesn't work
},
{
"Name":"Lunch",
"Options":[{Name:"Macaroni",ID:1}, {Name:"PB&J",ID:2}, {Name:"Fish",ID:3}],
"SelectedOption":""
}
],
}, {
"firstName": "Jane",
"lastName": "Doe"
}];
});
Is this the one case where I should actually be using ng-init with a SelectedIndex on the model?

If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.
<select
ng-model="Choice.SelectedOption"
ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>
Updated fiddle http://jsfiddle.net/gFCzV/34/

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.
<select
ng-model="Choice.SelectedOption.ID"
ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

Using ng-selected for selected value. I Have successfully implemented code in AngularJS v1.3.2
<select ng-model="objBillingAddress.StateId" >
<option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>
</select>

Related

AngularJS ng-options ng-model option selected by id

Why this code doesn't work as expected? I expect China be selected in the select but it is empty.
<div ng-app="app">
<div ng-controller="appController" class="p-2" ng-init="init()">
<select
name="user_country"
class="form-control"
ng-model="country"
ng-options="item.id as item.title for item in countries track by item.id">
<option value="" disabled>Select Country</option>
</select>
</div>
</div>
Controller:
var app = angular.module('app', []).controller('appController', ['$scope', function($scope){
$scope.country = 3
$scope.countries = [
{id: 1, title: 'US'},
{id: 2, title: 'Japan'},
{id: 3, title: 'China'},
{id: 4, title: 'Russia'}
]
}])
I expect to see China rather than an empty field. Here is a CodePen example https://codepen.io/grinev/pen/YJERvz.
Udpated the ng-options to
ng-options="item.id as item.title for item in countries">
Answer
without track By - JSFiddle
with track By - JSFiddle
track by just helps Angular internally with array sorting as far as I know. The value of the options is defined by the first argument (in your case item). If you want it to be by id then you should use item.id as item.name for item in items
You need to be storing the object, not the id. So instead of $scope.country = 3; you need to put it after the countries array and set it to $scope.country = $scope.countries[2];

Angular js ng-options selecting blank label. when i select it not showing selected

When i am selecting from dropdown it bind into model but the label of selection showing blank.
<select class="form-control" ng-options="data as data.field for data in reportAnalysis.categoryFields track by data.id" ng-model="reportAnalysis.testData">
<option value="" selected disabled>---Select---</option>
</select>
Any solution Please help?
As per the data that you mentioned, your select statement should be categoryFields.response. Not sure if you have already set your categoryFields to hold response object directly. Also the data that you shared has a square bracket and curly brace missing, assuming it to be a typo error. You can check working jsfiddle link for more clarity
<select class="form-control" ng-options="data as data.field for data in reportAnalysis.categoryFields.response track by data.id" ng-model="reportAnalysis.testData">
<option value="" selected disabled>---Select---</option>
</select>
jsfiddle : https://jsfiddle.net/caq0ne1d/27/
Let me know if this helped.
var app = angular.module("Profile", [])
app.controller("ProfileCtrl", function($scope) {
$scope.reportAnalysis = {}
$scope.reportAnalysis['categoryFields'] = [{
"id": 178,
"field": "Attachments",
"sort_order": 1,
"field_type": [{
"id": 178,
"type": 5,
"is_mandatory": 0,
"conditional_field_id": 0,
"conditional_field_value": ""
}]
}]
$scope.reportAnalysis['testData'] = {}
$scope.update_data = function() {
console.log($scope.reportAnalysis['testData'])
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="Profile" ng-controller="ProfileCtrl">
<select class="form-control" ng-options="data as data.field for data in reportAnalysis.categoryFields track by data.id" ng-model="reportAnalysis.testData" ng-change="update_data()">
<option value="" selected disabled>---Select---</option>
</select>
</body>

how to show default dropdown value show top angularjs

I have a dropdown show below card information and i want to show is_default= true card show top other cards below.. please help me
<select ng-model="approvedinvoicesCtrl.currentcard.card_id">
<option ng-value="item.card_id" ng-repeat="item in approvedinvoicesCtrl.current_job.cards ">{{item.brand +' '+ item.last_digits}}</option>
</select>
{brand:"Visa",
card_id:"card_19VHhAGdj8iWoXDURuRqNH28",
last_digits : 123123,
is_default:true},
{
brand:"Master",
card_id:"card_19VHhAGdj8iWoXDURuRqNH28",
last_digits : 123123,
is_default:false}
Suggesting you with this
<select>
<option ng-value="item.card_id" ng-repeat="item in dropdownval "
ng-selected=item._default >
{{item.brand +' '+ item.last_digits}}</option>
</select>
LIVE DEMO
I will suggest to use ngOptions on option element instead of ng-repeat.
Note: ngOptions provides an facility for the "option" element which should be used instead of ngRepeat when you want the select model to be bound to a non-string value. This is because an option element can only be bound to string values at present. For more information you can check this link.
Working demo with ngOptions :
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.current_job = {
"cards": [
{
brand:"Visa",
card_id:"card_19A",
last_digits : 123123,
is_default:true
}, {
brand:"Master",
card_id:"card_19B",
last_digits : 123123,
is_default:false
}
]
};
for (var i in $scope.current_job.cards) {
if ($scope.current_job.cards[i].is_default == true) {
$scope.topCard = $scope.current_job.cards[i].card_id;
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select ng-options="item.card_id as item.brand+' '+item.last_digits for item in current_job.cards"
ng-model="topCard">
</select>
</div>
Working demo with ngRepeat :
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.current_job = {
"cards": [
{
brand:"Visa",
card_id:"card_19A",
last_digits : 123123,
is_default:true
}, {
brand:"Master",
card_id:"card_19B",
last_digits : 123123,
is_default:false
}
]
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select ng-model="currentcard.card_id">
<option ng-value="item.card_id" ng-repeat="item in current_job.cards" ng-selected="item.is_default">{{item.brand +' '+ item.last_digits}}</option>
</select>
</div>
You should use the ng-init and the ng-options for defaults values like:
<select ng-init="somethingHere = options[1]"
ng-model="somethingHere"
ng-options="option for option in options">
</select>
$scope.options = [
'Brand1',
'Brand2',
'Brand3'
];
You can use orderby
<select ng-model="approvedinvoicesCtrl.currentcard.card_id><option ng-value="item.card_id" ng-repeat="item in approvedinvoicesCtrl.current_job.cards | orderBy:'is_default':false">{{item.brand +''+ item.last_digits}}</option></select>
Here item 'is_default' property is sorted in a reversed order. The 2nd argument can be any order function, so you can sort in any rule.
#link http://docs.angularjs.org/api/ng.filter:orderBy
You may prefer pre-selecting the card (option selected) instead of sorting using the default card at the top.
You can use the ng-selected using the default value if no value is selected in ng-model , otherwise, it selects the value in ng-model.
<select ng-model="currentCard.selected" >
<option
ng-value="item.card_id" ng-repeat="item in cards"
ng-selected="(currentCard.selected==item.card_id) || (!currentCard.selected && item.is_default)">
{{item.brand +' '+ item.last_digits}}
</option>
</select>
or you can use the ng-options approach. In this last case, you can pre-select an option using the ng-model value only.
<select
ng-model="currentCard.selected"
ng-options="item.card_id as item.brand+' '+item.last_digits for item in cards">
</select>
See this fiddle with both examples:
https://jsfiddle.net/hdca55cg/
The second one shows default card if you have previously selected in the model.

How to display states of a country if two specific countries are chosen from a list of countries in Angular ng-repeat

I have a list of countries, and the client has the option to choose two of these. When the client uses the checkbox tick to choose two countries (by clicking on the checkboxes of two countries), we need to display the states in those two countries using ng-repeat.
Can someone please help me with a small example of the unordered lists and how to use ng-repeat in this scenario?
I am new to Angular.
As far as the HTML, something like the below is a very simple example of what you may end up with. You could use two ng-repeats; one for each country selected, and another for each state within each country:
<div ng-repeat="country in countries">
<h1>country.name</h1>
<ul>
<li ng-repeat="state in country.states">
<p>state.name</p>
</li>
</ul>
</div>
You can create checkboxes which add a "checked" property to the countries. And then a repeat which repeats only checked ones.
View
<p>
Choose {{limit}} countries:
</p>
<p ng-repeat="country in countries">
<input type="checkbox" ng-model="country.checked" ng-disabled="(countries | filter:{checked:true}).length >= limit"> {{country.name}}
</p>
<p>
Result
</p>
<div ng-repeat="country in countries | filter:{checked:true}">
<h1>{{country.name}}</h1>
<ul>
<li ng-repeat="state in country.states">
<p>{{state}}</p>
</li>
</ul>
</div>
</div>
Controller
angular.module("app", [])
.controller("mainCtrl", function($scope) {
$scope.limit = 2;
$scope.countries = [{
"name": "Finland",
"states": [
"statename1",
"statename2"
]
}, {
"name": "Sweden",
"states": [
"statename3",
"statename4"
]
}, {
"name": "Norway",
"states": [
"statename5",
"statename6"
]
}];
});
Demo: https://jsfiddle.net/ptfg5xs0/1/

Angular: ng-options add custom directive

I want to create a select tag with 'selected' value. I am doing this with ng-repeat since I cannot add a custom directive to ng-options. This is the code.
<select class="ng-valid ng-dirty" ng-model="selectedCity">
<option ng-repeat="city in allCities" value="{{city.id}}" after-render-cities>{{city.name}}</option>
</select>
This adds an extra option with value =?string:1? which I searched a lot. Since ng-options solves this issue, I however have to add the directive after-render-cities for each option. How can I solve this issue?
Use this
<select class="ng-valid ng-dirty" ng-model="selectedCity" ng-options="city.id as city.name for city in allCities">
</select>
for selection of first value, write following code in your controller
$scope.selectedCity = $scope.allCities[0].id;
use ng-init for solve value =?string:1?
<select class="ng-valid ng-dirty" ng-model="selectedCity" ng-init='selectedCity=allCities[0].id'>
<option ng-repeat="city in allCities" value="{{city.id}}" after-render-cities>{{city.name}}</option>
</select>
another choice you can use ng-selected fiddle
<option ng-repeat="(key,city) in allCities" ng-selected='key==0' value="{{city.id}}" after-render-cities>{{city.name}}</option>
</select>
You can create a custom directive, using select and ng-options.
Snippet:
JS:
template: "<select ng-options='item.id as item.name for item in list' ng-model='data'></select>",
HTML:
<div select-option list="list" ng-model='data'></div>
Refer to the demo here.
Try this code
Java Script
var app = angular.module('myApp', []);
app.controller('SampleController', function ($scope) {
$scope.Cities = [
{ Id: 1, Name: "New York" },
{ Id: 2, Name: "Colombo" },
{ Id: 3, Name: "Real Madrid" },
{ Id: 4, Name: "Bostan" },
{ Id: 5, Name: "Birmingham" }
];
$scope.City= 3;
});
HTML
<select ng-options="C.Id as C.Name for C in Cities" ng-model="City"></select>
Read This Blog, it has everything explained.

Resources