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

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>.

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>

dropdown is not populating with json object

my ng-model value is - "{"Id":1,"Description":"Draft","Code":"Draft"}" and ng-options are -
[
{
"Id": 1,
"Description": "Draft",
"Code": "Draft"
},
{
"Id": 2,
"Description": "UserSubmitted",
"Code": "UserSubmitted"
},
{
"Id": 3,
"Description": "PLMApproved",
"Code": "PLMApproved"
}
]
so my dropdown is not populating(but value is binding).
I understatnd, if ng-model values is just a integer value it would bind, then how about json object?
Please help needed.
AFAIK it won't bind because your model is a different object i.e. points to a different memory location and it doesn't match with any objects inside the array.
You could use the as clause in ng-options to select a property you want to get into the ng-model and setting ng-model with that value will set the selected option.
e.g.
<select ng-options="item.Id as item.Description for item in default.items" ng-model="default.selectedItemId">
<option value="">Select</option>
</select>
else you could use the track by clause which is used when you want to get one property or object into your ng-model but you want to set the selected option with another property from the ng-model which will be specified in the track by clause i.e. update the binding from code to the view
e.g.
<select ng-options="item as item.Description for item in default.items track by item.Id" ng-model="default.selectedItem">
<option value="">Select</option>
</select>

Data binding with ng-option dropdown in Angular

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

AngularJS - default value of select (id fields are named differently)

I have the following data (provided from an Angular service, stored in the controller) I need to use to populate a drop-down, and also select the default value. When the page renders, the first dropdown option is "?" and is selected by default. The second dropdown option is "Name 1".
I've read around and tried different things, so I'm wondering if this is caused the track by being based on an id field with a different name (id vs. otherId)? Any ideas?
For the dropdown:
{"someDataSet":
[
{"id": "1", "name": "Name 1"},
{"id": "2", "name": "Name 2"}
]
}
For selecting the default value:
{"otherDataSet":
{"otherId": "1", "otherName": "Name 1"}
}
My front-end code:
<select ng-options="someData.name for someData in controller.someDataSet
track by someData.id" ng-model="controller.otherDataSet.otherId"/>
Thanks!
Check this solution: http://codepen.io/tzach/pen/LVKeGJ
Adding an option element will set the default value until your real data is loaded:
<option value="{{ controller.otherDataSet.otherId }}">{{ controller.otherDataSet.otherName }}</option>

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