AngularJS : get select label without modifying ng-model - javascript

I'm currently stuck with a problem which seems simple :
Controller :
$scope.fruits = [{
name: 'AP',
label: 'Apple'
}, {
name: 'BA',
label: 'Bananas'
}];
HTML code :
<select
ng-model="meal.fruit"
ng-options="fruit.name as fruit.label for fruit in fruits">
</select>
<p>Fruit : {{meal.fruit}}</p>
Problem is, this displays
Fruit : BA
Instead of
Fruit : Bananas
I can't modify ng-option to "fruit as fruit.label" because I need my model "meal.fruit" to be "AP" or "BA" (because it is a java enum deserialize by Jackson, and it requires the Enum value).
JSFiddle
In summary, I need meal.fruit to be "BA" and I also want to be able to display the selected value "Bananas" somewhere else.
What can I do ?
EDIT :
The solution that worked for me was found by Maxim Shoustin, (many thanks !) :
I modified my code to have the following :
http://jsfiddle.net/2qfSB/77/
And then I modified my submit method to add the following :
$scope.meal.fruit = $scope.meal.fruit.name;

Just change ng-options:
ng-options="fruit.label as fruit.label for fruit in fruits">
Fixed Demo: Fiddle
as a side note
You can set by default 1st element to avoid empty combo by using ng-init:
<select
ng-model="meal.fruit"
ng-options="fruit.label as fruit.label for fruit in fruits"
ng-init="meal.fruit = fruits[0].label"
>
Demo: Fiddle

Related

Ng-init in the selection for default value with AngularJS doesn't work

In web app I have a list of Expenses, which that if you press above it takes you to a new page to edit the selected Expense. When the user click on an element of list, I save the Object (the selected Expense) in a Global Object common in whole application and I retrieve it when I am in the Editing controller:
$scope.companySelected = GlobalApplicationData.selectedExpenseList;
The GlobalApplicationData.selectedExpenseList is an Object:
$$hashKey: "object:39"
_id: "33aa5549-7802-40d9-bc89-8780705b8c9b"
_rev: "3-eb940cb990524112723f711618e0cf51"
ad_table_id: 1000596
company_name: "Company 1"
data: Object
recordid: 1000005
__proto__: Object
In one expense there is only one company.
So, in this page of editing I have some field (input type text, date, etc). And I also have a selection with the list of the Companies of the logged user. To retrieve that list, I made this function:
$scope.getCompanyList = function() {
EditExpenseListSrv.getCompanyListDetail(user).then(function (companyListDetail) {
$scope.companyList = companyListDetail;
$scope.$apply();
}).catch(function (err) {
console.log(err);
});
};
CompanyListDetail is an array of Obejct:
companyListDetail: Array[5]
0: Object
1: Object
2: Object
3: Object
4: Object
And this is one example of those object:
_id: "44e620dc-e715-453f-882b-3f21aeef48fe"
_rev: "1-c09c9f3350e853e588f3358aaafc0374"
ad_table_id: 1000146
data: {
description: "text"
id_company: 513424
name: "Company 2"
}
recordid: 1000002
So the company of the selected Expense ($scope.companySelected) will definitely part of the list obtained by the query ($scope.companyList). But I want to give the user the possibility to change it.
So I would like to make a selection containing the list ($scope.companyList) and default already selected the Company corresponding to $scope.companySelected.
I've writter this, but it doesnt work:
<select class="selection" ng-model="companySelected"
ng-init="companySelected = globalApplicationData.selectedExpenseList"
ng-options="company
as company.data.name for company in companyList">
But it doesn't work. I can see in the selection all the Companies, but don't select the default value
When you are assigning a default value to the select, you need to assign the object, so it won't work, when assigned with the same data of some other object:
Note:
a) data is the array which is getting looped in the select list
b) selectedcountry is the model which is bind on select list.
Option 1:
Using ng-init:
<select ng-model="selectedcountry" ng-init="selectedcountry = data[0]" ng-options="item.name for item in data">
<option value="">Select</option>
</select>
Demo 1.
Option 2:
Assigning the default from the controller
$scope.selectedcountry = $scope.data[0];
Demo 2
You can try to do the initialisation in the controller:
$scope.companySelected = "the value that you want to set here"
Or you can try to put the ng-init inside the parent of the select. Once I had a problem like this and I solved it putting the ng-init in the parent tag. Example:
<div id="parent" ng-init="companySelected = globalApplicationData.selectedExpenseList">
<select ...>
</div>
Another idea would be to put companySelected inside an object. I have had some problems (I am not sure why) with the forms if I was using $scope.value inside the ng-value instead of using $scope.formData.value

Add options to my Select2

I have one problem. I use Select2 in my page, and I would like to modify it a little. This is my example:
<select id="mySelect" multiple>
<!-- -->
</select>
var data = [{
id: 1,
text: "sample_1",
version: "1"
},{
id: 2,
text: "sample_2",
version: "2"
}]
$("#mySelect").select2({
data: data
});
JSFIDDLE example
In this example displays the text from the downloaded JSON. But what if I wanted a to modify the search? When entering text, it appears next to a third value version with JSON, but if I click on value version will not add to select.
Eg. When i Search in select, my select looks like:
- text_1 - "version"
- text_2 - "version"
but if I click some option, for example text_1, that only adds to the select box text_1 no version, that is, as far. I think that the example of Templating shows a bit of my problem. Only when you click, for example, in Alaska flag disappears and the text remains in the select
Any suggestions how I can do this?
With templateSelection and templateResult you can control both the search results and the view of selected item
$("#mySelect").select2({
data:data,
templateSelection: function(val) {
return val.text +" - " + "version" + val.version;
},
templateResult: function(val) {
return val.text +" "+ val.version;
}
});

Select default value at ng-options

I have this code and information:
$scope.options = [
{ id: 1, label: "My label" },
{ id: 2, label: "My label 2" }
];
$scope.selected = 2;
<select ng-options="opt.label for opt in options" ng-model="selected">
<option value="">Select one</option>
</select>
However, the options are created like this:
<select ng-options="opt.label for opt in options" ng-model="selected">
<option value="">Select one</option>
<option value="0">My label</option>
<option value="1">My label 2</option>
</select>
How can I set the selected option to My label 2? I know it can be done:
$scope.selected = $scope.options[1];
But my problem is that option is created in a directive, and at that moment I don't know 1) how many values has $scope.options, nor 2) what is the index of the selected option in database. The only thing I know is the id (which is in the object).
The html of my directive is something like this:
<select ng-switch-when="select" ng-model="form.model[element.model]" ng-options="{{element.rule}}"></select>
Where element.rule is:
rule: "role.role for role in element.options"
And element.options has the array with options, and form.model[element.model] has the id of the option selected.
How can I get the index of the element with ID X in the array $scope.options? I'm very sure that will give me the solution, but I don't know how to do it...
Just set the correct model value when initiating the controller. You can easily get the correct array value if you know the ID by using a filter:
$scope.selected = $filter('filter')($scope.options, {id: 2})[0];
The issue with your code as I see it is that the 'selected' value coming out of your database is the ID of the object selected and not the object itself. This is fine but because of that difference you can't simply set
$scope.selected = 2 //assuming 2 is the value coming from your database
because the value '2' does not exist in your option array. The Object with an ID of 2 does.
If you can always guarantee the options you have in the option array are from 1-n and in that order, you can accomplish this by simply using this instead:
$scope.options = [
{ id: 1, label: "My label" },
{ id: 2, label: "My label 2" }
];
var selectedIdFromDatabase = 2;
$scope.selected = $scope.options[selectedIdFromDatabase-1];
If you can't make that guarantee (and even if you can for now, it may not be a good idea to make that assumption in your code) you'll need iterate over the array of objects you have to identify the object with an ID of the selectedId from your database.
The answer to this question has a great write-up about the type of data-processing you'll need to do and a lot more information about javascript objects in general.

angularjs - remove option from input select

Can't figure this out for the life of me. Using AngularJS.
I have a dropdown Select field with several options. It is a part of a form that may be completed multiple times (ie "add another" type form). Now, one of the options may only be used once. How can I remove this option from all other select fields after it has been used?
What I'm working with:
html
<select ng-model="item.itemtype">
<option ng-repeat="i in itemtype" value="{{i}}" ng-init="item.itemtype = itemtype[0]">{{i}}</option>
</select>
angularjs
$scope.Items = [
{ 'itemtype': '', 'desc': '', 'color': '' }
];
$scope.itemtype = [
'shirt',
'pants',
'hats',
'shoes',
'special'];
What I've tried (and really doesn't work)
$scope.specialremove = function() {
var exist = Items.indexOf("special")
if (exist !== 0) {
return '';
}
else {
return 'special';
}
}
I'm hoping I don't have to turn to any other framework to solve this. Feel free to point out any other problems/errors/inefficiencies in my code.
The first thing that can help is using ng-options:
ng-options="type for type in itemType".
It would be better to have objects with label and value properties, in order to write it as
ng-options="type.value as type.label for type in itemType"
and separate the displayed label from the actual value of the selection.
In your controller you should have something like:
$scope.itemType= [
...
];
$scope.selectedItem= $scope.itemType[0];
So that you can write the select as:
<select ng-Model="selectedItem" ng-options="item.value as item.label for item in itemType"></select>
To remove a selected item you can watch the value of selectedItem in the controller: when it matches the value you want, remove it from the array and update selectedItem accordingly.
Here is a basic fiddle. I simply remove the third option after selecting it, and reset the selected item to the first.

AngularJs's ng-options - clarification?

I have this small demo.
Basically , it's a select element with this data :
address: {
select: {
code: "0",
name: "Select proof of address"
},
letter: {
code: "1",
name: "Letter"
},
photograph: {
code: "2",
name: "Photograph"
}
}
And here is the select
<select ng-model="current.addressCode" ng-options="value.code as value.name for (key,value) in student.address"</select>
Questions:
Question #1 - Looking at the Ng doc -
And so , I try to compare
value.code as value.name for (key,value) in student.address
to the second line ( which i find most appropriate)
select as label for (key , value) in object
What is going on here ?
value.code goes to select ???
Html select element has an option tag with value and inside text like :
<option value="volvo">Volvo</option> thats' all.
What did they mean in their docs ?
Question #2
How can I bind this object of myne to a regular sane value,text select ?
(I want the code to be the value and the name to be as text)
Currently I dont see any value in the dom :
You are correct in understanding that example two fits your needs, that is:
select as label for (key , value) in object
Here, as the documentation mentions:
select: The result of this expression will be bound to the model of the
parent <select> element. If not specified, select expression will
default to value.
So, for your use case, your existing code for the select tag is correctly structured:
<select ng-model="current.addressCode" ng-options="value.code as value.name for
(key,value) in student.address"></select>
value.code value is stored in current.addressCode while, in the select dropdown, you should see value.name as the options label.
EDIT: So, to answer your questions:
Question 1
In this case, "select" is just a variable name - a placeholder if you may like for the documentation to explain about it (which it does further below). In your code, the value of the variable that is used instead of select is the one that gets bound to the select's ng-model (In your case, value.code)
Question 2
Exactly as you have mentioned:
<select ng-model="current.addressCode" ng-options="value.code as value.name for
(key,value) in student.address"></select>
This will give you the necessary value, text select tag automatically. When you select an option, the value.code associated with that option gets stored in current.addressCode
http://jsfiddle.net/7FL76/1/
how about this:
it requires simple change :
address: [
{
code: "0",
name: "Select proof of address"
},
{
code: "1",
name: "Letter"
},
{
code: "2",
name: "Photograph"
}
]
the reason is your Key is same as nested Name ( like, letter - Letter ) , so json is a bit redundant.
as result you will see.
value as a code, and text as a name .

Categories

Resources