Pregunta

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; 
    }
}
¿Fue útil?

Solución

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(); 
}

Otros consejos

This is odd, but you can get the binding between ng-options and ng-model to work by forcing a cast to occur in the comprehension expression:

ng-options="id*1 as name for (id, name) in items" 

Here is a fork of your fiddle demonstrating this trick: http://jsfiddle.net/wittwerj/HMjnV/9/

Having said that, I do prefer Marc's approach of converting toString in the controller.

Yes to pre-populate the value like you have done then definitely it should be a string. Since the value attribute in option tag takes only String. But yes in AngularJs you can give references like this given in the fiddle . And the workaround to your problem will be converting id to string.

JS Objects have property name-value pairs.
value can be of any type, but name is always a string.
Although you think you define it as a number, it is automatically converted to string. There is no way you can change that (i.e. create an object with number property-names).

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