Pregunta

I'm having trouble using AngularJS to filter a json object into a select form element. Here's what I've got so far. I'm stumped, any help would be appreciated.

app.js:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.showItems = null;
  $scope.items = [
    { id: '023', name: 'foo' },
    { id: '033', name: 'bar' },
    { id: '010', name: 'blah' }];
});

singlepageapp.html:

<html data-ng-app="app">
  <body data-ng-controller="MainCtrl">
    <form>
    <select data-ng-model="showItems" data-ng-options="item as item.name for item in items"></select>
    </form>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
    <script src="app.js"></script>
  </body>
</html>

current result:

<select data-ng-model="selectedItem" ng-options="item as item.name for item in items" class="ng-pristine ng-valid">
    <option value="?" selected="selected"></option>
    <option value="0">foo</option>
    <option value="1">bar</option>
    <option value="2">blah</option>
</select>

desired result:

<select data-ng-model="selectedItem" ng-options="item as item.name for item in items" class="ng-pristine ng-valid">
    <option value="?" selected="selected"></option>
    <option value="023">foo</option>
    <option value="033">bar</option>
    <option value="010">blah</option>
</select>
¿Fue útil?

Solución

You can always just repeat over options in the html and not use data-ng-options. I've made a fiddle that does what you want: http://jsfiddle.net/5MQ9L/

<select ng-model="selected">
    <option value="{{item.id}}" ng-repeat="(i,item) in items"> {{item.name}}
    </option>
</select>

This way you can set the values directly with scoped vals.

Hope this helped!

Otros consejos

You should have specified the item.id

<select ng-model="selected" ng-options='item.id as item.name for item in items'>               </select>

From http://docs.angularjs.org/api/ng/directive/select

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.

I updated the jsFiddle http://jsfiddle.net/5MQ9L/1/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top