Not able to get select value in scope - angularjs

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!

Related

Angularjs - Set default option in select with dynamic ng-model

I have this problem: i created a selects inside a ng-repeat, the ng-model of each select is dinamically generated.
I need to set a default value to these selects, but i don't know how i can do this
HTML
<div ng-controller="ricercaAttivita">
<div class="accordion-group" ng-repeat="masterAttribute in masterAttributes">
<select class="trip dark" ng-change = "search(1, true, true)" ng-model="masterAttribute.Id" ng-options="attr.Id as attr.Value for attr in masterAttribute.Values">
<option value="">Tutte</option>
</select>
</div>
</div>
APP.JS
var tantoSvagoApp = angular.module('tantoSvagoApp');
tantoSvagoApp.controller("ricercaAttivita", function ($scope) {
$scope.masterAttributes = {"id" : "11", nome" : "MARCHE", "values" :
[{ "id": "114", "nome": "ANCONA" }, { "id": "116", "nome": "ASCOLI PICENO" }]
},
{"id" : "12", nome" : "LOMBARDIA", "values" :
[{ "id": "120", "nome": "MILANO" }, { "id": "121", "nome": "BERGAMO" }]
};
});
The ng-model of my select is "masterAttribute.Id", i need to loop every generated select and, in certain conditions, set a particular default option selected.
Something like
$scope.masterAttribute.Id = value;
How i can do this?
Anyone can hel me PLEASE?
just set the selected value object to $scope.masterAttribute. In your controller add
$scope.masterAttribute = masterAttribute.Values[0];
hope this will help.
$scope.masterAttributes should be an array [],
$scope.masterAttributes=[{
"id": "11",
nome " : "
MARCHE ", "
values " : [{
"id": "114",
"nome": "ANCONA"
}, {
"id": "116",
"nome": "ASCOLI PICENO"
}]
},
{
"id": "12",
nome " : "
LOMBARDIA ", "
values " : [{
"id": "120",
"nome": "MILANO"
}, {
"id": "121",
"nome": "BERGAMO"
}]
And finally set default value in select is,
$scope.masterAttribute = $scope.masterAttributes[0].values[0];

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

Give styling to select option group

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>

Angular JS orderBy not working using dropdown

i am trying to do orderBy using dropdown value, but its not working :(
CODE:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.datas = [{
"id": "1",
"name": "name area 1"
}, {
"id": "2",
"name": "name area 2"
}, {
"id": "3",
"name": "name area 3"
}, {
"id": "4",
"name": "name area 4"
}];
$scope.dropdown = [{
"title": "Newest first",
"value": "true"
}, {
"title": "Oldest first",
"value": "reverse"
}];
});
HTML:
<div ng-app="myApp">
<div ng-controller="myCtrl">
<ul ng-repeat="rows in datas | orderBy: 'id':orderByData">
<li>{{rows.id}} : {{rows.name}}</li>
</ul>
<select ng-model="orderByData" ng-options="x.value as x.title for x in dropdown"></select>
</div>
</div>
DEOM JS BIN
Why you use reverse?
Please use false instead reverse and it should work fine.
$scope.dropdown = [{
"title": "Newest first",
"value": "true"
}, {
"title": "Oldest first",
"value": "false"
}];
You don't need reverse parameter here. Instead you can do something like this:
<ul ng-repeat="rows in datas | orderBy: getSort()">
<li>{{rows.id}} : {{rows.name}}</li>
</ul>
Where getSort is defined as:
$scope.getSort = function() {
return $scope.orderByData ? 'id' : '-id';
};
Basically you want sort part to look like orderBy: 'id' or orderBy: '-id'.
Demo: http://jsbin.com/pepureta/1/edit?html,js,output

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