Search code examples
javascriptjsonangularjsng-options

filtering a json object with ng-options angular js


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>

Solution

  • 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!