balicekt
balicekt

Reputation: 613

Angular ng-model select option first element empty

HTML:

<select ng-model="item.visible">
        <option value="0">NO</option>
        <option value="1">YES</option>
</select>

ITEM:

$scope.item.visible = 1; //doesn't work
$scope.item.visible = "1" //works fine

I absolutely don't understand why first solution doesn't work and my problem is that I'm getting this value from database and I can't change it to string. I think solution could be use a directive. But I'm sure there will be much better solution. Thanks for help.

Upvotes: 1

Views: 666

Answers (1)

dfsq
dfsq

Reputation: 193261

It doesn't work because Angular uses strict comparison of the model value with the value bound to option. If you can't use string value as model you could cast it in HTML with ngInit directive:

<select ng-model="item.visible" ng-init="item.visible=item.visible + ''">
    <option value="0">NO</option>
    <option value="1">YES</option>
</select>

then it will work with both $scope.item.visible = 1; and $scope.item.visible = "1";.

Demo: http://plnkr.co/edit/kZJbVRtyHQ19LUbDALFx?p=preview

Upvotes: 1

Related Questions