Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-options with object data source

I'm struggling to understand how ng-options works with a data source. I've read the docs and I feel like I'm doing exactly what is required, but I still get problems when attempting.

<!DOCTYPE html>  <html ng-app="app">    <head>      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js">              </script>      <link rel="stylesheet" href="style.css" />      <script type="text/javascript">        angular.module('app', [])        .controller('IndexCtrl', ['$scope', function($scope) {          $scope.types = {            1: "value1",            2: "value2",            5: "value3"          };        }]);      </script>    </head>    <body ng-controller="IndexCtrl">      <select ng-model="type" ng-options="k as v for(k, v) in types">        <option value="">Select Type</option>      </select>    </body>  </html>

I always get this error in the console:

Error:

Expected ngOptions in form of 'select (as label)? for (key,)?value in collection (track by expr)?' but got 'k as v for(k, v) in types'.

What am I doing incorrectly?

See plunkr here:

http://plnkr.co/edit/Bl6u4151KyDkxhYrsdCm?p=preview

like image 772
colefner Avatar asked Dec 05 '13 06:12

colefner


People also ask

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 selected 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.

How do ng-options work?

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.

What is Ng option?

The ng-options Directive in AngularJS is used to build and bind HTML elements with options to a model property. It is used to specify <options> in a <select> list. It is designed specifically to populate the items on a dropdown list. This directive implements an array, in order to fill the dropdown list.


1 Answers

This is kind of strange, but it seems like you need to put a space after for. This works:

<select ng-model="type" ng-options="k as v for (k, v) in types">   <option value="">Select Type</option> </select> 
like image 183
Jayantha Lal Sirisena Avatar answered Oct 27 '22 22:10

Jayantha Lal Sirisena