Give styling to select option group - angularjs

How to give a styling to select option group using ng-options ?
HTML:
<select ng-model="filteredBy" ng-options="obj_data.value as obj_data.title group by obj_data.group for obj_data in data"></select>
JS:
$scope.filteredBy = 'true';
$scope.data = [{
"group": "byStatus",
"title": "ACTIVE",
"value": "false"
}, {
"group": "byStatus",
"title": "COMPLETED",
"value": "true"
}, {
"group": "byColor",
"title": "Blue",
"value": "#27a9e3"
}, {
"group": "byColor",
"title": "Green",
"value": "#28b779"
}];
In the above example i want to give styling to color (Blue & Green).
How to do that using ng-options` ?
DEMO PLUNKR

if u want to give color to option then you have to use ng-repeat instead of ng-option then set the background-color using ng-style...
<select ng-model="filteredBy">
<option ng-repeat="val in data" ng-style = "{'background':val.value}" >{{val.title}}</option>
</select>
for grouping u need to modify data as below
js
$scope.filteredBy = 'true';
$scope.data = [{
'group': 'byStatus',
'content':[{'title': 'ACTIVE','value': 'false'}, {'title': 'COMPLETED','value': 'true'
}]}, {
'group': 'byColor',
'content':[{'title': 'Blue','value': '#27a9e3'}, {'title': 'Green',
'value': '#28b779'}]
}];
html
<select ng-model="filteredBy">
<optgroup ng-repeat="val in data" label={{val.group}} >
<option ng-repeat="v in val.content" ng-style = "{'background':v.value}" >{{v.title}}</option>
</optgroup>
</select>

Related

Using ng-repeat and $index how to set default selected in select

Using ng-repeat and $index how to show default selected value using angularjs
my code :
I have SelectValues :
"Jewelery_And_Diamond_Type": [
{
"id": 33,
"value": "Earrings"
},
{
"id": 35,
"value": "Gemstones"
},
{
"id": 34,
"value": "Loose Diamonds"
},
{
"id": 32,
"value": "Necklaces"
},
{
"id": 31,
"value": "Pendants"
},
{
"id": 30,
"value": "Rings"
} ]
selected Value is "Earings"
In my HTML
<select ng-model="categoryval.Jewelery_And_Diamond_Type[$index]" ng-init="categoryval.Jewelery_And_Diamond_Type[$index] = SelectValues.Jewelery_And_Diamond_Type.indexOf(0)" ng-options="option.value for option in SelectValues.Jewelery_And_Diamond_Type track by option.id">
If I wrote like this means no value as selected by default. I need exact selected Values based on the $index.
Use ng-options
<select ng-model="value" ng-init="value='Earrings'" ng-options="mode.value as mode.value for mode in storageResult.Jewelery_And_Diamond_Type">
</select>
DEMO
In a select, ng-model will determine which option is selected.
So if you strictly want to select an item by its index in the array you need to create the object model like so:
$scope.selected = $scope.values[0];
values being your json array.
The select will then look like:
<select
ng-model="selected"
ng-options="option.value for option in values track by option.id">
</select>
Don't use ng-init in the html, it's bad practice.
function MyController() {
this.values = [
{
"id": 33,
"value": "Earrings"
},
{
"id": 35,
"value": "Gemstones"
},
{
"id": 34,
"value": "Loose Diamonds"
},
{
"id": 32,
"value": "Necklaces"
},
{
"id": 31,
"value": "Pendants"
},
{
"id": 30,
"value": "Rings"
} ];
this.selected = this.values[0];
};
angular.module('app', []);
angular.module('app')
.controller('MyController', MyController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController as ctrl">
<select
ng-model="ctrl.selected"
ng-options="option.value for option in ctrl.values track by option.id">
</select>
<br>
{{ctrl.selected | json}}
</div>
</div>
If you know the id where default selected value is available you can include it in a scope variable and inject the variable in
<option value="">{{selectedType}}</option>
$scope.selectedType= categoryval.Jewelery_And_Diamond_Type[defaultIndex].valu‌​e
value ="" helps you to fill the empty first option
Remove ng-init and set default value in controller so that you can unit test whether default option is always what you want it to be.
In controller:
$scope.defaultValue = $scope.SelectValues.Jewelery_And_Diamond_Type[0];
then change HTML
<select ng-model="defaultValue" ng-options="option.value for option in SelectValues.Jewelery_And_Diamond_Type track by option.id">
Plunker

ng-selected is not working with ng-model in select box - Angularjs [duplicate]

This question already has answers here:
AngularJS: ng-selected doesn't show selected value [duplicate]
(2 answers)
Closed 4 years ago.
While ng-model is used in select box and ng-selected is also used in options with some condition that time ng-selected is not working.
If I will remove ng-model than ng-selected is working, but if i will remove ng-model than how I should get the value of select box in controller.
Please help !
Here is my code...
HTML:
<select class="form-control" ng-change="accessModeSelected()">
<option ng-selected="mode.status == '1'" ng-repeat="mode in storageResult.accessMode" ng-value="mode.name" name="accessMode{{$index}}" id="accessMode">
{{mode.name}}
</option>
</select>
AngularJS:
$scope.storageResult = {
"storageAccount":"Enable",
"user": "sdcard",
"pass": "sdcard",
"wifiIP": "0",
"ipAddr": "0",
"accessMode": [
{"name": "Local Storage","status": "0"},
{"name":"WiFi Storage", "status": "1"},
{"name":"Internet Storage", "status": "0"}
]
}
Use ng-options and ng-init(for setting default value) instead of ng-repeat.
ng-options is specifically for select
<select class="form-control" ng-init="statusselect='WiFi Storage'" ng-model="statusselect" ng-options="mode.name as mode.name for mode in storageResult.accessMode">
</select> Selected Value : {{statusselect}}
FIDDLE
Edit: Using ng-repeat
I would prefer ng-options,but if you want to use ng-selected with ng-repeat you'll need provide a default selected value to ng-model from your controller
<select class="form-control" ng-model="statusselect">
<option ng-selected="{{mode.name == statusselect}}" ng-repeat="mode in storageResult.accessMode" value="{{mode.name}}" name="accessMode{{$index}}" id="accessMode">
{{mode.name}}
</option>
</select> Selected Value : {{statusselect}}
Inside Controller
$scope.storageResult = {
"storageAccount":"Enable",
"user": "sdcard",
"pass": "sdcard",
"wifiIP": "0",
"ipAddr": "0",
"accessMode": [
{"name": "Local Storage","status": "0"},
{"name":"WiFi Storage", "status": "1"},
{"name":"Internet Storage", "status": "0"}
]
}
$scope.statusselect = $scope.storageResult["accessMode"][1]["name"];
FIDDLE
Use ng-options instead of ng-repeat
<select ng-model="status" ng-options="mode.status as mode.name for mode in storageResult.accessMode">
and In controller
app.controller("dobController", ["$scope", "$http",
function($scope, $http) {
$scope.storageResult = {
"storageAccount": "Enable",
"user": "sdcard",
"pass": "sdcard",
"wifiIP": "0",
"ipAddr": "0",
"accessMode": [{
"name": "Local Storage",
"status": "0"
}, {
"name": "WiFi Storage",
"status": "1"
}, {
"name": "Internet Storage",
"status": "0"
}]
};
$scope.status = '1';
}
]);
DEMO
I'm sure there are many ways to answer this question and a lot of answers have been provided,but based on OP's question on how to send 'mode.name' into ng-model I've explained below using ng-options.
In your JS
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope", "$http",
function($scope, $http) {
$scope.storageResult = {
"storageAccount": "Enable",
"user": "sdcard",
"pass": "sdcard",
"wifiIP": "0",
"ipAddr": "0",
"accessMode": [{
"name": "Local Storage",
"status": "0"
}, {
"name": "WiFi Storage",
"status": "1"
}, {
"name": "Internet Storage",
"status": "0"
}]
};
$scope.status = $scope.storageResult.accessMode[0].name;
$scope.selectedItem = '';
}
]);
In your HTML to bind mode name to ng-model follow this.
<select ng-model="status" ng-options="mode.name as mode.name for mode in storageResult.accessMode">
To bind entire object you can try below syntax
<select ng-model="status" ng-options="mode as mode.name for mode in storageResult.accessMode">
For this make small change in your JS $scope.status like
$scope.status = $scope.storageResult.accessMode[0];
Here is a DEMO plunker

What would be angular ng-option equivalent of this select?

I am struggling to get this into an ng-option. Is it even possible?
<select ng-model="detail_type_id">
<optgroup ng-repeat="type in data.detailTypes" label="{{type.name}}">
<option ng-repeat="t in type.children" value="{{t.id}}">{{t.name}}</option>
</optgroup>
</select>
DetailTypes looks like this:
[
{"id":7,
"parent_id":null,
"name":"Contact",
"children":[
{"id":8,
"parent_id":7,
"name":"Address",
"children":[]
},
{"id":12,
"parent_id":7,
"name":"Something else",
"children":[]
}
]},
{"id":16,
"parent_id":null,
"name":"Other",
"children":[
{"id":10,
"parent_id":16,
"name":"Remarks",
"children":[]}
]
}
]
Child id needs to be selected. Nesting cannot be deeper.
The ngOptions directive does not work with multidimensional objects. So you need to flatten your array to use it.
I wrote a filter for that:
app.filter('flatten' , function(){
return function(array){
return array.reduce(function(flatten, group){
group.children.forEach(function(child){
child.groupName = group.name;
flatten.push(child)
})
return flatten;
},[]);
}
})
And the HTML part would be like this:
<select ng-model="detail_type_id"
ng-options="item.id as item.name
group by item.groupName for item
in data.detailTypes | flatten track by item.id">
</select>
Plunker (version #1 with filter):
https://plnkr.co/edit/dxi7j8oxInv2VRJ1aL7F
I also modified your object to be like this:
[{
"id": 7,
"parent_id": null,
"name": "Contact",
"children": [{
"id": 8,
"parent_id": 7,
"name": "Address",
"children": []
}, {
"id": 12,
"parent_id": 7,
"name": "Something else",
"children": []
}]
}, {
"id": 16,
"parent_id": null,
"name": "Other",
"children": [{
"id": 10,
"parent_id": 16,
"name": "Remarks",
"children": []
}]
}]
EDIT:
After suggestion I wrote another version without the filter, but flattening the array inside the controller.
Additional Controller JS:
$scope.flattenDetailTypes = flattenDetailTypes($scope.data.detailTypes);
function flattenDetailTypes(array){
return array.reduce(function(flatten, group){
group.children.forEach(function(child){
child.groupName = group.name;
flatten.push(child)
})
return flatten;
},[]);
}
Markup:
<select ng-model="detail_type_id"
ng-options="item.id as item.name group by item.groupName for item in flattenDetailTypes track by item.id"></select>
Plunker (version #2 without filter):
https://plnkr.co/edit/D4APZ6

Not able to get select value in scope

I have code like one attached in js fiddle. It is very basic, I am trying to get value of the select when it changes using scope variable. But i am not able to.Is there any specific reason why it is not working.
<div ng-controller="myCtrl">
<select
ng-model="myOption"
ng-options="value.id as value.label group by value.group for value in myOptions" ng-change="selectedValue()">
<option>--</option>
</select>
<div>
ng-model value: {{myOptionnew}}
</div>
</div>
var app = angular.module('myExample', []);
function myCtrl($scope) {
$scope.myOptions = [{
"id": 106,
"group": "Group 1",
"label": "Item 1"
},{
"id": 107,
"group": "Group 1",
"label": "Item 2"
},{
"id": 110,
"group": "Group 2",
"label": "Item 3"
}];
$scope.selectedValue = function()
{
alog($scope.myOption);
$scope.myOptionnew = $scope.myOption;
}
};
http://jsfiddle.net/jm6of9bu/1107/
In the fiddle the function alog is not defined. Therefore the assignment that follows doesn't occur.
Remove alog or replace it with $log.log : fiddle
As a side note, you also need to add value="" to the default empty option if you want it to be displayed:
<option>--</option>
should be:
<option value="">--</option>
HTML:
<div ng-controller="myCtrl">
<select
ng-model="myOption"
ng-options="value.id as value.label group by value.group for value in myOptions">
<option>--</option>
</select>
<div>
ng-model value ID: {{myOptionnew}}
</div>
JS :
var app = angular.module('myExample', []);
function myCtrl($scope) {
$scope.myOptions = [{
"id": 106,
"group": "Group 1",
"label": "Item 1"
},{
"id": 107,
"group": "Group 1",
"label": "Item 2"
},{
"id": 110,
"group": "Group 2",
"label": "Item 3"
}];
$scope.$watch('myOption', function(result){
if (result)
$scope.myOptionnew = result;
});
};
I used $watch try this!

How to set a selected option of a dropdown list control using angular JS

I am using Angular JS and I need to set a selected option of a dropdown list control using angular JS. Forgive me if this is ridiculous but I am new with Angular JS
Here is the dropdown list control of my html
<select ng-required="item.id==8 && item.quantity > 0" name="posterVariants"
ng-show="item.id==8" ng-model="item.selectedVariant"
ng-change="calculateServicesSubTotal(item)"
ng-options="v.name for v in variants | filter:{type:2}">
</select>
After it gets populated I get
<select ng-options="v.name for v in variants | filter:{type:2}" ng-change="calculateServicesSubTotal(item)"
ng-model="item.selectedVariant" ng-show="item.id==8" name="posterVariants"
ng-required="item.id==8 && item.quantity > 0" class="ng-pristine ng-valid ng-valid-required">
<option value="?" selected="selected"></option>
<option value="0">set of 6 traits</option>
<option value="1">5 complete sets</option>
</select>
How can I set the control for value="0" to be selected?
I hope I understand your question, but the ng-model directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant. This means that changing item.selectedVariant in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant has a value of 0, that item should get selected.
If variants is an array of objects, item.selectedVariant must be set to one of those objects. I do not know which information you have in your scope, but here's an example:
JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
This would leave the "b" item to be selected.
I don't know if this will help anyone or not but as I was facing the same issue I thought of sharing how I got the solution.
You can use track by attribute in your ng-options.
Assume that you have:
variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]
You can mention your ng-options as:
ng-options="v.name for v in variants track by v.id"
Hope this helps someone in future.
If you assign value 0 to item.selectedVariant it should be selected automatically.
Check out sample on http://docs.angularjs.org/api/ng.directive:select which selects red color by default by simply assigning $scope.color='red'.
i see here already wrote good answers, but sometime to write the same in other form can be helpful
<div ng-app ng-controller="MyCtrl">
<select ng-model="referral.organization" ng-options="c for c in organizations"></select>
</div>
<script type='text/javascript'>
function MyCtrl($scope) {
$scope.organizations = ['a', 'b', 'c', 'd', 'e'];
$scope.referral = {
organization: $scope.organizations[2]
};
}
</script>
Simple way
If you have a Users as response or a Array/JSON you defined, First You need to set the selected value in controller, then you put the same model name in html. This example i wrote to explain in easiest way.
Simple example
Inside Controller:
$scope.Users = ["Suresh","Mahesh","Ramesh"];
$scope.selectedUser = $scope.Users[0];
Your HTML
<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>
complex example
Inside Controller:
$scope.JSON = {
"ResponseObject":
[{
"Name": "Suresh",
"userID": 1
},
{
"Name": "Mahesh",
"userID": 2
}]
};
$scope.selectedUser = $scope.JSON.ResponseObject[0];
Your HTML
<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>
It can be usefull. Bindings dose not always work.
<select id="product" class="form-control" name="product" required
ng-model="issue.productId"
ng-change="getProductVersions()"
ng-options="p.id as p.shortName for p in products">
</select>
For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".
$scope.issue.productId = productId;
function activate() {
$http.get('/product/list')
.then(function (response) {
$scope.products = response.data;
if (productId) {
console.log("" + $("#product option").length);//for clarity
$timeout(function () {
console.log("" + $("#product option").length);//for clarity
$('#product').val('number:'+productId);
//$scope.issue.productId = productId;//not work at all
}, 200);
}
});
}
Try the following:
JS file
this.options = {
languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);
HTML file
<div class="form-group col-sm-6">
<label>Preferred language</label>
<select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
</select>
</div>
This is the code what I used for the set selected value
countryList: any = [{ "value": "AF", "group": "A", "text": "Afghanistan"}, { "value": "AL", "group": "A", "text": "Albania"}, { "value": "DZ", "group": "A", "text": "Algeria"}, { "value": "AD", "group": "A", "text": "Andorra"}, { "value": "AO", "group": "A", "text": "Angola"}, { "value": "AR", "group": "A", "text": "Argentina"}, { "value": "AM", "group": "A", "text": "Armenia"}, { "value": "AW", "group": "A", "text": "Aruba"}, { "value": "AU", "group": "A", "text": "Australia"}, { "value": "AT", "group": "A", "text": "Austria"}, { "value": "AZ", "group": "A", "text": "Azerbaijan"}];
for (var j = 0; j < countryList.length; j++) {
//debugger
if (countryList[j].text == "Australia") {
console.log(countryList[j].text);
countryList[j].isSelected = 'selected';
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<label>Country</label>
<select class="custom-select col-12" id="Country" name="Country" >
<option value="0" selected>Choose...</option>
<option *ngFor="let country of countryList" value="{{country.text}}" selected="{{country.isSelected}}" > {{country.text}}</option>
</select>
try this on an angular framework
JS:
$scope.options = [
{
name: "a",
id: 1
},
{
name: "b",
id: 2
}
];
$scope.selectedOption = $scope.options[1];

Resources