Search code examples
javascriptangularjsng-options

ng-options dont work with an object


Im sure there's a perfectly good explanation for this, but i cant seem to make ng-options work with my model object. Basically i would like to make my select show a list of countries. Option values are country codes and labels are country names:

HTML

<div ng-app="demoApp">
    <div ng-controller="UserInfoCtrl">
        <h1>User Info</h1>

        <label>Email</label>
        <input type="text" ng-model="user.email" />
        <br />

        <label>Country</label>
        <select ng-model="user.country" ng-options="code as name (code, name) in countriesByCode">
        </select>

        <pre>{{ user | json }}</pre>
    </div>
</div>

JavaScript

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

demoApp.controller("UserInfoCtrl", function($scope) {
    $scope.user = { };

    $scope.countriesByCode = {
        'AF' : 'Afghanistan',
        'CA' : 'Canada',
        'RU' : 'Russia'
    };
});

Here's the jsfiddle


Solution

  • You are missing a 'for' in your statement

    code as name for (code, name) in countriesByCode
    

    Here is the corrected fiddle: http://jsfiddle.net/8XJX4/2/

    hope this helps.