How do ng-options
and ng-repeat
differ?
In the following code, I have an ng-repeat
that iterates through a list of people:
<select ng-model="selectedPerson" > <option ng-repeat="obj in people" value="{{obj.id}}">{{obj.name}}</option> </select>
Here is what I believe to be an equivalent select box in using ng-options
:
<select ng-model="selectedPerson" ng-options='obj.name for obj in people'></select>
I would expect them to behave the same, but they do not. Why?
$scope.people = [ { id: 0, name: 'Leon', music: [ 'Rock', 'Metal', 'Dubstep', 'Electro' ] },
Definition and Usage. The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
Definition and Usage. 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.
You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using 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.
From the documentation:
Note: ngOptions provides an iterator facility for the element which should be used instead of ngRepeat when you want the select model to be bound to a non-string value. This is because an option element can only be bound to string values at present.
This fiddle makes the point more clear: select2 will bind to select 1 but not the other way around. Click the buttons and the reason will reveal itself :-)
HTML
<div ng-app ng-controller="MyCtrl"> <select ng-model="selectedPerson" > <option ng-repeat="obj in people" value="{{obj.id}}"> {{obj.name}} </option> </select> <select ng-model="selectedPerson" ng-options="p.id as p.name for p in people"> </select> selected: {{selectedPerson}} {{typeofSelectedPerson()}} <button ng-click="selectedPerson=2">Jao</button> <button ng-click="selectedPerson='1'">Ze</button> </div>
JS
function MyCtrl($scope){ $scope.selectedPerson = 1; $scope.people = [ { id: 1, name: 'Ze' }, { id: 2, name: 'Jao' } ]; $scope.typeofSelectedPerson = function(){ return typeof $scope.selectedPerson; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With