Data binding with ng-option dropdown in Angular - angularjs

I have a dropdown and I want to display a value based on the dropdown selection in Angular. I am using ng-options and figure a simple data binding should work, but the data binding isn't showing up. Here's a plunker: http://plnkr.co/edit/IptAt3e5EZi15OObfWFr?p=preview
<select ng-model="defcom"
ng-options="opt.DefCom as opt.DefCom for opt in acct_info | filter:{Req:'MUST'}:true" >
</select>
<select ng-model="defcust"
ng-options="opt.Customer as opt.Customer for opt in cust_info | filter: {Com: defcom}: true">
</select>
<p>{{ cust_info.Name }}</p>
in the controller:
$scope.cust_info = [
{
"Customer": "1",
"Com": "1",
"Name": "First Name"
},
{
"Customer": "2",
"Com": "1",
"Name": "Second Name"
},
{
"Customer": "3",
"Com": "4",
"Name": "Third Name"
}];

{{cust_info[defcust-1].Name}} should work as expected

In this line:
{{cust_info.Name}}
you are trying to reference Name incorrectly, you have an array of objects which each have Name therefore that will not work.
Change it to:
{{cust_info[defcust - 1].Name}}
-1 because "Customer" starts at 1 and not 0
and you will get the nth index inside cust_info, where the nth index was selected by the user and stored into defcust.
http://plnkr.co/edit/WHkijq8ea0ATnO4JXnc9?p=preview

Without using the index to achieve this needs a little more javascript in there I guess.. I've added some. Hope this helps.. See this demo
<select ng-model="defcom" ng-change="change_acc(defcom)"
ng-options="opt.DefCom as opt.DefCom for opt in acct_info | filter:{Req:'MUST'}:true" >
</select>
<select ng-model="defcust" ng-change="change_cust(defcust)"
ng-options="opt.Customer as opt.Customer for opt in cust_info | filter: {Com: defcom}: true">
</select>
http://plnkr.co/edit/pf6PtOWANfLxulQupqZq?p=preview

Related

pre select a value using ng-options in angular js [duplicate]

I've seen the documentation of the Angular select directive here: http://docs.angularjs.org/api/ng.directive:select.
I can't figure how to set the default value. This is confusing:
select as label for value in array
Here is the object:
{
"type": "select",
"name": "Service",
"value": "Service 3",
"values": [ "Service 1", "Service 2", "Service 3", "Service 4"]
}
The html (working):
<select><option ng-repeat="value in prop.values">{{value}}</option></select>
and then I'm trying to add an ng-option attribute inside the select element to set prop.value as the default option (not working).
ng-options="(prop.value) for v in prop.values"
What am i doing wrong?
So assuming that object is in your scope:
<div ng-controller="MyCtrl">
<select ng-model="prop.value" ng-options="v for v in prop.values">
</select>
</div>
function MyCtrl($scope) {
$scope.prop = {
"type": "select",
"name": "Service",
"value": "Service 3",
"values": [ "Service 1", "Service 2", "Service 3", "Service 4"]
};
}
Working Plunkr: http://plnkr.co/edit/wTRXZYEPrZJRizEltQ2g
The angular documentation for select* does not answer this question explicitly, but it is there. If you look at the script.js, you will see this:
function MyCntrl($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.color = $scope.colors[2]; // Default the color to red
}
This is the html:
<select ng-model="color" ng-options="c.name for c in colors"></select>
This seems to be a more obvious way of defaulting a selected value on an <select> with ng-options. Also it will work if you have different label/values.
* This is from Angular 1.2.7
This answer is more usefull when you are bringing data from a DB, make modifications and then persist the changes.
<select ng-options="opt.id as opt.name for opt in users" ng-model="selectedUser"></select>
Check the example here:
http://plnkr.co/edit/HrT5vUMJOtP9esGngbIV
<select name='partyid' id="partyid" class='span3'>
<option value=''>Select Party</option>
<option ng-repeat="item in partyName" value="{{item._id}}" ng-selected="obj.partyname == item.partyname">{{item.partyname}}
</option>
</select>
If your array of objects are complex like:
$scope.friends = [{ name: John , uuid: 1234}, {name: Joe, uuid, 5678}];
And your current model was set to something like:
$scope.user.friend = {name:John, uuid: 1234};
It helped to use the track by function on uuid (or any unique field), as long as the ng-model="user.friend" also has a uuid:
<select ng-model="user.friend"
ng-options="friend as friend.name for friend in friends track by friend.uuid">
</select>
I struggled with this for a couple of hours, so I would like to add some clarifications for it, all the examples noted here, refers to cases where the data is loaded from the script itself, not something coming from a service or a database, so I would like to provide my experience for anyone having the same problem as I did.
Normally you save only the id of the desired option in your database, so... let's show it
service.js
myApp.factory('Models', function($http) {
var models = {};
models.allModels = function(options) {
return $http.post(url_service, {options: options});
};
return models;
});
controller.js
myApp.controller('exampleController', function($scope, Models) {
$scope.mainObj={id_main: 1, id_model: 101};
$scope.selected_model = $scope.mainObj.id_model;
Models.allModels({}).success(function(data) {
$scope.models = data;
});
});
Finally the partial html model.html
Model: <select ng-model="selected_model"
ng-options="model.id_model as model.name for model in models" ></select>
basically I wanted to point that piece "model.id_model as model.name for model in models" the "model.id_model" uses the id of the model for the value so that you can match with the "mainObj.id_model" which is also the "selected_model", this is just a plain value, also "as model.name" is the label for the repeater, finally "model in models" is just the regular cycle that we all know about.
Hope this helps somebody, and if it does, please vote up :D
<select id="itemDescFormId" name="itemDescFormId" size="1" ng-model="prop" ng-change="update()">
<option value="">English(EN)</option>
<option value="23">Corsican(CO)</option>
<option value="43">French(FR)</option>
<option value="16">German(GR)</option>
Just add option with empty value. It will work.
DEMO Plnkr
An easier way to do it is to use data-ng-init like this:
<select data-ng-init="somethingHere = options[0]" data-ng-model="somethingHere" data-ng-options="option.name for option in options"></select>
The main difference here is that you would need to include data-ng-model
The ng-model attribute sets the selected option and also allows you to pipe a filter like orderBy:orderModel.value
index.html
<select ng-model="orderModel" ng-options="option.name for option in orderOptions"></select>
controllers.js
$scope.orderOptions = [
{"name":"Newest","value":"age"},
{"name":"Alphabetical","value":"name"}
];
$scope.orderModel = $scope.orderOptions[0];
If anyone is running into the default value occasionally being not populated on the page in Chrome, IE 10/11, Firefox -- try adding this attribute to your input/select field checking for the populated variable in the HTML, like so:
<input data-ng-model="vm.x" data-ng-if="vm.x !== '' && vm.x !== undefined && vm.x !== null" />
Really simple if you do not care about indexing your options with some numeric id.
Declare your $scope var - people array
$scope.people= ["", "YOU", "ME"];
In the DOM of above scope, create object
<select ng-model="hired" ng-options = "who for who in people"></select>
In your controller, you set your ng-model "hired".
$scope.hired = "ME";
It's really easy!
Just to add up, I did something like this.
<select class="form-control" data-ng-model="itemSelect" ng-change="selectedTemplate(itemSelect)" autofocus>
<option value="undefined" [selected]="itemSelect.Name == undefined" disabled="disabled">Select template...</option>
<option ng-repeat="itemSelect in templateLists" value="{{itemSelect.ID}}">{{itemSelect.Name}}</option></select>

ng-options not behaving as expected,as documented?

No matter what I try, the ID is always passed as the value. I want the Genre.label(string) as the value...
I am trying to get my head around ng-options, i read the docs, and the examples seem straight forward, however I am getting differet results than expected.
my model for Books is
Book: {
title: string,
genre: string,
description: string
}
and my model for Genre is
Genre: {
label: string
description: string
}
then when I use ng-init="getGenres()" to pull genres into my scope, I EXPECT using
ng-options="genre.label for genre in genres track by genre.label"
will use the LABEL for each iteration and populate the option value with the LABEL and as a matter of fact - Inspect Element does show that - it looks like this:
<option label="Sci-fi" value="Sci-fi">Sci-fi</option>
My DATA however ends up looking like this:
_id : 5a2f...5691
genre : "5a2f552765226c3018be9878"
title : "Blah Blah"
Here is the form in context:
<form ng-submit="addBook()" ng-init="getGenres()" >
<div class="form-group" >
<label>Title</label>
<input type="text" class="form-control" ng-model="book.title" placeholder="Title" >
</div>
<div class="form-group" >
<label>Genre</label>
<select class="form-control" ng-model="book.genre"
ng-options="genre.label for genre in genres track by genre.label" >
<option value="">-- choose genre --</option>
</select>
</div>
</form>
Here is the COLTROLLERs getGenres:
// get genres
$scope.getGenres = function() {
$http.get('/api/genres')
.success(function(response) {
$scope.genres = response;
});
}
it returns:
[{
"_id": "5a2f5.....a065b",
"label": "Sci-fi",
"description": "Dealing with subject matter that combines fictional worlds and science, both real and theoretical."
}, {
"_id": "5a2f5.....9877",
"label": "Romance",
"description": "Topics with amorous overtone, undertones and toneless rantings. Matters of the heart. Emotional folly and frolic."
}, {
"_id": "5a2f5.....9878",
"label": "Suspense",
"description": "Events dealing with an arousal of anticipation and dread, mostly in equal parts."
}, {
"_id": "5a2f5.....9879",
"label": "Gobbeldegook",
"description": "nonsensical gibberish. blather, post-moderistic drivel."
}, {
"_id": "5a2f5.....987a",
"label": "Drama",
"description": "Drama Drama Drama Drama Drama Drama Drama"
}, {
"_id": "5a2f5.....987b",
"label": "NonFiction",
"description": "Real life crap. No fakery or literary license, this is REAL!"
}]
Any help is much appreciated
-cheers
you should use like this:
<select class="form-control" ng-model="book.genre"
ng-options="genre.label as genre.label for genre in genres track by genre.label" >
<option value="">-- choose genre --</option>
</select>
If you don't use genre.label as , the genre will be used as the model in this case.
The expression BEFORE as, which is genre.label, will be used as model value.
The expression after as, which is genre.label will be used as displayed value in options.

Angularjs - ng-model not working for select while using ng-repeat and ng-selected

I have set my ng-repeat in options along with ng-selected, but option is not getting selected, When I remove ng-model from select all become working.
HTML code:
<select ng-model="formData.value">
<option value="{{item.value}}" ng-selected="{{((item.value).indexOf(formData.value) != -1 ? true:'') == formData.value}}" ng-repeat="item in levels">{{ item.name}}</option>
</select>
Controller code:
$scope.levels= [
{"value": ["1", "2", "3"],"name": "High"},
{"value": ["4", "5", "6"],"name": "Medium"},
{"value": ["7", "8", "9"],"name": "Low"}
]
What I am doing here is, if the formData.value is between 1 to 3, i would like to show the dropdown field with High...
Its working fine without ng-model name, however I would like to get a value from the user and save it in the array. In that scenario, the dropdown doesn't show the selected field...

How to set Pre selected data in dynamic select option in IONIC

I face a strange problem where I need to show Pre selected data(which also come from server) in select option. The problem that I need to show select option based on key and value option.
<div class="list list-inset">
<span class="input-label">Permisstion</span>
<select ng-model="permisstion" >
<option ng-repeat="(key, value) in Roles" id="{{key}}" value="{{value}}">{{value}}</option>
</select>
</div>
JSON Data
"Roles": {
"21": "Admin",
"22": "Main Manager",
"23": "Branch Manager",
"26": "Side Manager"
}
I don't no how to show Pre selected data in select option and I try a lot but till now I don't get success.
Please help.
Firt, your JSON is not a array of objects. I dont know if work in a <select> by objects atributes... by my other answer you can do something like in below.
Try to use like that:
"Roles" : {
[
{code: 21, name: "Admin"},
{code: 22, name: "Main Manager"},
{code: 23, name: "Branch Manager"},
{code: 24, name: "Side Manager"}
]
}
So the atribute "code" will be my index to the select:
<select ng-options="role.name for role in Roles track by role.code">
<option value="">They see me rollin</option>
</select>
What I do was use track by role.code, as you can watch in this video.
REMEMBER: If code reapet in the array of objects it will break the <select>.

ng-options not selecting last item in option array

I have a weird problem that I'm not able to reproduce on Plunker. When the first option 'user' is set in the model, the select displays it properly and it is set to 'user'. When I load another user with role:'admin', the select is set to blank option.
In my controller I define:
$scope.roles = ['user', 'admin'];
My $scope.user object looks like this:
{
"_id": "54f1f8f7e01249f0061c5088",
"displayName": "Test1 User",
"provider": "local",
"username": "test1",
"__v": 0,
"updated": "2015-03-02T07:41:42.388Z",
"created": "2015-02-28T17:20:55.893Z",
"role": "admin",
"profileImageURL": "modules/users/img/profile/default.png",
"email": "test1#user.com",
"lastName": "User",
"firstName": "Test1"
}
In my view:
<select id="role" class="form-control" data-ng-model="user.role" data-ng-options="role for role in roles"></select>
When I reverse the roles array $scope.roles = ['admin', 'user']; then admins are displayed properly, and 'user' won't be set as selected.
Strangely if I add a third item to the array $scope.roles = ['user', 'admin', 'joe']; Then the first two 'user' and 'admin' will be set selected properly, and the last one 'joe' won't.
Any ideas?
--- UPDATE ---
The generated select markup looks like this:
<select id="role" class="form-control ng-pristine ng-valid" data-ng-options="role for role in roles" data-ng-model="user.role">
<option value="? string:joe ?"></option>
<option value="0" selected="selected" label="admin">admin</option>
<option value="1" label="user">user</option>
<option value="2" label="joe">joe</option>
</select>
Just got done battling this. My model $scope.details.source, is being populated by ajax, causing the issue. (i.e. select would not init to last item in array when that was returned by ajax, other values init'ed OK). I did find a work around. I had
$scope.sources = ["1", "2", "3", "4", "5", "6", "7", "8"];
<select ng-model="details.source" ng-options="item for item in sources"> </select>
and changed it to:
$scope.sources = [{index:0, value:"1"}, {index:1, value:"2"}, {index:2, value:"3"}, {index:3, value:"4"}, {index:4, value:"5"}, {index:5, value:"6"}, {index:6, value:"7"}, {index:7, value:"8"}];
<select ng-model="details.source" ng-options="item.index as item.value for item in sources"> </select>
I found that the problem didn't exist when the model was initialized in the controller as opposed to ajax. Donno why ... but it works.
I made all combinations with you suggest, but the error doesn't occur.
Please look for my tests:
http://plnkr.co/edit/jzfhD3D60fhj8yFqBqgJ?p=preview
<h3>select</h3>
<select ng-model="role" ng-options="item for item in roles"></select>
<h3>original</h3>
<select id="role" class="form-control" data-ng-model="user.role" data-ng-options="role for role in roles"></select>
Try to verify your angularjs version. Maybe can be a specific version error.
I'm posting a workaround, but not a solution nor explanation for the problem above. If anyone has actual info why this is happening, and how to make this work with arrays, please share and I'll be happy to accept it as an answer.
I changed the options from a simple array to an array of objects:
$scope.roles = [{name:'Admin',value:'admin'},{name:'User', value:'user'}];
And my view to:
<select data-ng-model="user.role" data-ng-options="role.value as role.name for role in roles"></select>
Thanks to Ilya Luzyanin for the help and directions!
Probably late, but here's a solution that helped me. I always add a virtual invisible option which is last in the list and never gets selected.
<select class="form-control"
ng-options="r as r for r in myList | orderBy track by r"
ng-model="item">
<option ng-show="false"></option> <!-- TRICK: select last value too -->
</select>

Resources