Using $index with the AngularJS 'ng-options' directive? - angularjs

Say that I bind an array to a select tag using the following:
<select ng-model="selData" ng-options="$index as d.name for d in data">
In this case, the associated option tags are assigned a sequence of index values: (0, 1, 2, ...). However, when I select something from the drop-down, the value of selData is getting bound to undefined. Should the binding actually work?
On the other hand, say that I instead do the following:
<select ng-model="selData" ng-options="d as d.name for d in data">
Here, the option tags get the same index, but the entire object is bound on change. Is it working this way by design, or this behavior simply a nice bug or side-effect of AngularJS?

Since arrays are very similar to objects in JavaScript, you can use the syntax for "object data sources". The trick is in the brackets in the ng-options part:
var choices = [
'One',
'Two',
'Three'
];
In the template:
<select
ng-model="model.choice"
ng-options="idx as choice for (idx, choice) in choices">
</select>
In the end, model.choice will have the value 0, 1, or 2. When it's 0, you will see One; 1 will display Two, etc. But in the model, you will see the index value only.
I adapted this information from "Mastering Web Application Development with AngularJS" by PACKT Publishing, and verified at the Angular reference documentation for select.

Since you can't use $index but you can try indexOf.
HTML
<div ng-app ng-controller="MyCtrl">
<select
ng-model="selectedItem"
ng-options="values.indexOf(selectedItem) as selectedItem for selectedItem in values"></select>
selectedItem: {{selectedItem}}
</div>
Controller
function MyCtrl($scope) {
$scope.values = ["Value1","Value2"];
$scope.selectedItem = 0;
}
Demo Fiddle
Comment:
Array.prototype.indexOf is not supported in IE7 (8)

$index is defined for ng-repeat, not select. I think this explains the undefined. (So, no, this shouldn't work.)
Angular supports binding on the entire object. The documentation could be worded better to indicate this, but it does hint at it: "ngOptions ... should be used instead of ngRepeat when you want the select model to be bound to a non-string value."

You can also use ng-value='$index' in <option> tag.
<select ng-model="selData">
<option ng-repeat="d in data track by $index" ng-value="$index">
{{d.name}}
</option>
</select>

Don't use $index inside select tags. Use $index inside the option tags if you want to use the array indexes as either values or options.
<option ng-repeat="user in users" value="{{user.username}}">{{$index+1}}</option>
If you want to use inside values just put it in the value attribute as binding expression like
<option ng-repeat="user in users" value="{{$index+1}}">{{user.username}}</option>
and my controller code be like:
var users = ['username':'bairavan', 'username':'testuser'];

Related

Angular Select show a different text once selected

I am using AngularJS (1.5) and im trying to create a select dropdown that can display a different text when selected vs shown in dropdown options
Option example {id: 1, name: 'text', selected: 'this was selected'}
Given the example above, how can i show the name property when they open the dropdown but the selected property after the option is selected?
You have a couple options for dropdowns in angularjs. If you're going the ng-repeat route, then if you have an array of objects structured like your example, then this would work:
<select ng-model="selectedItem">
<option ng-repeat="item in items" value="item.selected"> {{item.name}} </option>
</select>
This will display the "name" in the dropdown, but since value=item.selected, it will assign the "selected" value to your ng-model.
Alternatively, you can do ng-options for the select and something like this would work:
<select ng-model="selectedItem"
ng-options="item.selected as item.name for item in items">
</select>
This does the same thing, but ng-options tends to allow more flexibility as you can assign entire objects to your model rather than just strings like ng-repeat only allows, plus angular claims it's faster.
Hope this helps. See here for more info https://docs.angularjs.org/api/ng/directive/select

Angular ng-model ng-selected

I want to bind a model value to selected item
<select id="hours" ng-model="v.T_Hour">
<option ng-repeat="n in [].constructor(24) track by $index" ng-selected="{{$index==v.T_Hour}}" value="{{$index}}">{{$index>9?$index:"0"+$index}}:00</option>
</select>
I want after the page loads , the value of the model 'v.T_Hour' to be selected in select , i assign the value of the model in the controller, when i view the resulting HTML i see that the value is selected in the HTML code ,but not selected in the select control , and the select control displays an empty item.
Try this
<select
name="name"
id="id"
ng-options="option.name for option in v.data track by option.value"
ng-model="v.selected"
class="form-control inline-forms">
<option value="" selected>{{placeHolder}}</option>
</select>
and in controller
$scope.v = {data:[], selected:{}, placeHolder:""}
$scope.v.data = [{name:"nameOne", value:"valueOne"},{name:"nameTwo", value:"valueTwo"},{name:"nameThree", value:"valueThree"}]
$scope.v.selected = $scope.v.data[0]
$scope.v.placeHolder = "Click to Select"
According Angular documentation ngOption is better way to go than ngRepeat:
Choosing between ngRepeat and ngOptions
In many cases, ngRepeat can be used on elements instead of ngOptions to achieve a similar result. However, ngOptions provides some benefits:
more flexibility in how the 's model is assigned via the select as part of the comprehension expression
reduced memory consumption by not creating a new scope for each repeated instance
increased render speed by creating the options in a documentFragment instead of individually
Specifically, select with repeated options slows down significantly starting at 2000 options in Chrome and Internet Explorer / Edge.
see: https://docs.angularjs.org/api/ng/directive/select

use ng-options or ng-repeat in select?

I want use select in angularjs.
I have a json that every element have 2 part: name and value. I want show name in dropdown and when user select one of theme, value is copy to ng-model.
$scope.list = [{name:"element1",value:10},{name:"element2",value:20},{name:"element3",value:30}];
For this I have 2 way to use select:
ng-options:
I use ng-options like below:
<select ng-model="model.test" ng-options="element.name for element in list"></select>
It's work correctly, but when I select each of element, I want just value of element is copy to ng-model, but a json is copy to ng-model, like below:
$scope.model.test = {name:"element1",value:1}
I can resolve this problem in angular controller, but I want find a better way that resolve this problem.
For resolove this problem, I use second way:
2.use ng-repeat in options:
<select ng-model="model.test">
<option ng-repeat="element in list" value="{{element.value}}">{{element.name}}</option>
</select>
In second way, just value is copy to ng-model, but as a string type:
$scope.model.test = "10";
I use below code, but all of them return a string value to model.
<option ng-repeat="element in list" value={{element.value}}>{{element.name}}</option>
<option ng-repeat="element in list" value="{{element.value}}|number:0">{{element.name}}</option>
<option ng-repeat="element in list" value={{element.value}}|number:0>{{element.name}}</option>
How can fix this problem?
you can resolve it with ng-options as well
ng-options="element.value as element.name for element in list"
please read this blog to understand more about ng-options.
Also another advantage of ng-options is, it binds the object as opposed to json string in case you want to attach the selected object to ng-model.
Have you tried this :
<select ng-model="model.test" ng-options="element.value element.name for element in list"></select>
btw, if you may have hundreds of records into your list, you should create your own directive, where you would manipulate your DOM with a simple javascript for loop
ng-repeat will be slow to be rendered,
ng-options adds every record into $watch.

Angular adds strange options into select element when setting model value

I have a select element defined as such:
<select name="country_id" id="country_id" required="required" ng-model="newAddressForm.country_id">
<option value="">Select Country</option>
<option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option>
</select>
All works fine when I'm not setting any kind of value in the directive which contains this select element. But when I do something like newAddressForm.country_id = 98, instead of selecting the option with value 98, Angular injects a new one at the top of the select element, like so:
<option value="? string:98 ?"></option>
What gives? What sort of format is this and why does this happen? Note that if I do a console.log(newAddressForm.country_id) in the directive, I get a normal "98", it's just weird in the generated HTML.
Edit: Situation update. Switched to using ng-select, but the issue persists.
The weird element no longer appears, BUT, now there's another element at the top, one that has only a question mark ? as the value, and no label.
That's, from what I gathered, Angular's "none selected" option. I still don't understand why it won't select the option I tell it to select, though.
Doing newAddressForm.country_id = 98 still gives no results. Why is that?
Using the following syntax with ng-options solved this problem for me:
<select name="country_id" id="country_id" required="required" ng-model="newAddressForm.country_id" ng-options="country.id as country.name for country in countries">
<option value="">Select Country</option>
</select>
Angular does not set the value of a select element to the actual values of your array and does some internal things to manage the scope binding. See Mark Rajcok's first comment at this link:
https://docs.angularjs.org/api/ng/directive/select#overview
When the the user selects one of the options, Angular uses the index
(or key) to lookup the value in array (or object) -- that looked-up
value is what the model is set to. (So, the model is not set to the
value you see in the HTML! This causes a lot of confusion.)
I'm not entirely sure using an ng-repeat is the best option.
If your values are integers you should use "" even if they're not strings, that simple reason is exactly why you're getting an option with a question mark as a value.
You shouldn't be using this:
{ value: 0, name: "Pendiente" },
{ value: 1, name: "Em andamento" },
{ value: 2, name: "Erro" },
{ value: 3, name: "Enviar email" },
{ value: 4, name: "Enviado" }
This is the right way:
{ value: "0", name: "Pendiente" },
{ value: "1", name: "Em andamento" },
{ value: "2", name: "Erro" },
{ value: "3", name: "Enviar email" },
{ value: "4", name: "Enviado" }
If you've at least one record which isn't using "" you'll be getting this ? option value.
I was running into this same problem earlier this evening, where I saw a select option showing up as the first in my list even though I didn't explicitly create it. I was filling a list of select options in my controller and using the same ng-options syntax mentioned above by jessedvrs (except that I was also inserting the "select an option" default option in the controller rather than marking it in the HTML like he was).
For some reason the select list would always show an additional option at index zero with a value of "?", but when I changed how I filled my default option in the controller, this issue went away. I was populating the select options by making an API call, filling them inside of a promise. I made the mistake of also populating my default "select an option" option as the first thing I did in that promise, but when I did this instead outside of the promise (prior to making the API call), the select options populated the way I waned them to.
I think jessedvrs option is one solution to the problem (setting the default option in the HTML markup), but if you prefer to populate your options in javascript instead, I would suggest to still set the default option prior to making any calls to an API or processes that may still be running while the HTML is being rendered.
When you assign a value to some select element, AngularJS looks for the provided value in the value attribute of the option tags in that select element. But the catch is, AngularJS does a type based comparison. So if the values in the option tags are strings (which usually is the case) and the variable you bind using ng-model is a number, AngularJS fails to find the matching option element and hence, creates its own element like this -
<option value="? integer:10 ?"></option>
The solution is, while binding itself, convert it to the appropriate type.
In this case, the solution would be to bind an Integer
<select name="country_id" id="country_id" required="required" ng-model="parseInt(newAddressForm.country_id)">
<option value="">Select Country</option>
<option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option>
</select>
If the values are set as Strings, the trick would be to use
<select ... ng-model="newAddressForm.country_id.toString()" >
use " track by 'value' " at the end of your ng-options :D
like the example below:
ng-options="country.id as country.name for country in countries track by country.id"
While pushing data on scope variable we can use following code
$scope.enquiryLocationRow.push({'location': EnqLocation.location, 'state_id': Number(EnqLocation.state_id), 'country_id': Number(EnqLocation.country_id)});
it resolved my issue
vm.kanoonCourses is object array, vm.courses is string array :
<table class="table table-hover">
<tr style="font-weight: bold; background-color: #dfedf8;">
<td>index</td>
<td>course in our system</td>
<td>course in outside system</td>
</tr>
<tr ng-repeat="course in vm.courses">
<td style="vertical-align: middle;">{{$index+1|persianNumber}}</td>
<td style="vertical-align: middle;">{{course.CourseTitle}}</td>
<td>
<select
ng-model="course.KanoonCourseTitle"
ng-options="option as option for option in vm.kanoonCourses">
</select>
</td>
</tr>
</table>

Angularjs ngOption with array

I want to add an html select with options AM,PM with angularjs,
what i need is having the key and the value of the option be the same :
<option value="AM">AM</option>
<option value="PM">PM</option>
My html looks like this
<select ng-model="ampm" ng-options="k as v for (k , v) in ampms"></select>
and my controller looks like
$scope.ampm = (new Date().getHours()) >= 12 ? 'PM' : 'AM';
$scope.ampms ={"AM":"AM","PM":"PM"};
and every thing working fine.
My question is why i cant have the same thing when i used an array (i tried all the options in the ng-options)
as this
$scope.ampms =["AM","PM"];
what ever i do i always get this
<option value="0">AM</option>
<option value="1">PM</option>
What i want is using an array like above with the option has the key and the value the same.
With AngularJS, you don't need to worry about what the value of the option is. All the selects I've seen with ng-options have values of 0 through whatever. If you're just looking for a dropdown with the two options, it can be as simple as
<select ng-model="ampm" ng-options="currOption for currOption in ['AM', 'PM']"></select>
See http://jsfiddle.net/EyBVN/1/
This is is a default behavior of ng-options in Angular. If you do not specify a key name, angular will automatically choose to use the index rather than a key. The code that does that can be seen on line 405 in /src/ng/directives/select.js on Angular's Github repository.
It can't even be forced by "value as value for (index, value) in values".
But as dnc253 just beat me to the punch with his answer (it showed up while I was typing)... you don't have to worry about it, Angular does it all for you automatically.
I did find a way to place specific data in the value of the options for a select. You have to add an ng-repeat attribute to the option tag inside the select tag:
<select id="{{question.id}}" name="{{question.id}}"
class="{{question.inputclass}}" ng-required="question.required"
title="{{question.title}}">
<option value=""></option>
<optgroup ng-repeat="group in question.data" label="{{group.group}}">
<option ng-repeat="item in group.data" value="{{item.value}}"
ng-selected="{{item.value == question.defaultValue}}">
{{item.description}}
</option>
</optgroup>
</select>
As a bonus, I left the option group tags in place to serve as an example for everyone.
The question.data JSON is:
[
{"group":"Canada","data":[{"value":"Ontario","description":"Toronto"},
{"value":"Quebec","description":"Quebec City"},
{"value":"Manitoba","description":"Winnipeg"}
]
},
{"group":"Mexico","data":[{"value":"Jalisco","description":"Guadalajara"},
{"value":"Nayarit","description":"Tepic"}
]
},
{"group":"United States of America","data":[
{"value":"Alabama","description":"Montgomery"},
{"value":"Georgia","description":"Atlanta"},
{"value":"Mississippi","description":"Jackson"},
{"value":"Louisiana","description":"Baton Rouge"},
{"value":"Texas","description":"Ausint"}
]
}
]

Resources