Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs ngOption with array

Tags:

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.

like image 518
ibmkhd Avatar asked Dec 03 '12 22:12

ibmkhd


People also ask

What is Ng option AngularJS?

AngularJS ng-options Directive The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.

What is the difference between Ng-options and Ng-repeat?

ng-repeat creates a new scope for each iteration so will not perform as well as ng-options. For small lists, it will not matter, but larger lists should use ng-options. Apart from that, It provides lot of flexibility in specifying iterator and offers performance benefits over ng-repeat.

How do I set default selected value in ng-options?

Use ng-init to set default value for ng-options .


2 Answers

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.

like image 42
Ben Lesh Avatar answered Oct 05 '22 11:10

Ben Lesh


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/

like image 150
dnc253 Avatar answered Oct 05 '22 11:10

dnc253