ng-options with object data source
Asked Answered
S

1

54

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

Specht answered 5/12, 2013 at 6:4 Comment(0)
I
108

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>
Ictinus answered 5/12, 2013 at 6:15 Comment(5)
Right you are! In fact, now that I take a closer look, the angular docs have the space as well. docs.angularjs.org/api/ng.directive:selectSpecht
This is due to the regular expression used to parse the ng-option clause.Xanthin
here you have example how to do it with select clause jsfiddle.net/6unbrp1eCloutier
@KrisJaklik, in your case the source is an array, not an object as OP asked.Estren
Hi can any one tell me why wee need to make "(k, v)" in ng-options="k as v for (k, v) in types" as we can do are work done by writing ng-options="k as v for v in types" also.Multinational

© 2022 - 2024 — McMap. All rights reserved.