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