Search code examples
angularjsng-options

Programmatically selecting ng-options bound to object data source


I have an ng-options select bound to an object. Setting the ng-model programmatically only works properly (updates the select) when setting it as a string. If I set the ng-model as an integer, it doesn't work. I really don't want to have to make this conversion. Is this the only way?

http://jsfiddle.net/HMjnV/1/

<div ng-controller="MyCtrl">
    <select ng-options="id as name for (id, name) in items" ng-model="selected"></select>
    <div>Selected ID: {{selected}} </div>
    <button ng-click="setSelected(1)">Set Selected to ID 1 as Integer</button>
    <button ng-click="setSelected('1')">Set Selected to ID 1 as String</button>
    <div>Programmatically setting the ng-model as string sets the dropdown but not as integer.</div>
</div>

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

function MyCtrl($scope) {
    $scope.items = {1: 'a', 2: 'b', 3:'c'};
    $scope.selected = null;

    $scope.setSelected = function(id) {
        $scope.selected = id; 
    }
}

Solution

  • EDITED

    You might try using toString when you programmatically set the model value, if you're looking for a quick and dirty solution. See @ExpertSystems answer for detail on the core of the problem.

    $scope.setSelected = function(id) {
        $scope.selected = id.toString(); 
    }