Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need example of select usage in AngularJS input form

Tags:

I am attempting to use an array of objects

 (array = [{name: 'Moe', id:1}, {name: 'Larry', id:2}, {name: 'Curly', id:3}])  

as a drop-down selection within an AngularJS input form, and I need an example badly. Can anyone point me to a jsFiddle that can enlighten me?

like image 939
explainer Avatar asked Feb 11 '13 17:02

explainer


People also ask

What is setPristine ()?

$setPristine(); This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false.

What is $setValidity in AngularJS?

The $setValidity() function is a built-in AngularJS function that is used to assign a key/value combination that can be used to check the validity of a specific model value. The key in this case is “unique” and the value is either true or false.

How do I filter with Ng-options?

In AngularJS when you are using ng-options, you can filter out the options by calling a custom function you have in the controller. Let's say you have following set of employees and when you display all these employees inside HTML select using ng-options, you can see all the employees in a dropdown.

How do I set default value in ng-options?

In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.


2 Answers

I would recommend using ng-options where you can.

<select ng-model="choice" ng-options="x.id as x.name for x in array"></select> 

Because check this out: You can use it to select actual objects:

app.controller('ExampleCtrl', function($scope) {     $scope.items = [         { id: 1, name: 'Foo' },         { id: 2, name: 'Bar' }     ];      $scope.selectedItem = null; }); 
<div ng-controller="ExampleCtrl">     <select ng-model="selectedItem"              ng-options="item as item.name for item in items"></select>      {{selectedItem | json}} </div> 

In the above example when you select something from the drop down, it's actually setting an entire object reference on selectedItem rather that just a value type.

NOTE: using ng-options sets your value="" attributes to the indices of the items in your collections this is by design.

It's really the best way to do it.

EDIT: more context as requested. Also here's a plunker showing it in use

like image 154
Ben Lesh Avatar answered Sep 28 '22 04:09

Ben Lesh


<select ng-model="choice">     <option ng-repeat="obj in array" value="{{obj.id}}">{{obj.name}}</option> </select> 

or use 'ng-options' - http://docs.angularjs.org/api/ng.directive:select

like image 42
Gal Ben-Haim Avatar answered Sep 28 '22 04:09

Gal Ben-Haim