AngularJS Select Not Binding To Ng-Model

Jeremy Wagner picture Jeremy Wagner · Dec 4, 2014 · Viewed 13.1k times · Source

My angular select isn't binding. I can tell the value is correct, but the select isn't updated. Why is not binding if the value is there?

<div ng-controller="MyController" ng-app>
    <select class="form-control" ng-model="colorId"ng-options="color.id as color.name for color in colorList">
        <option value="">--Select a Color--</option>
    </select>
<input type="button" value="submit" ng-click="Select()"></input>

function MyController($scope) {
    $scope.colorList = [{
        id: '1',
        name: 'red'
    }, {
        id: '2',
        name: 'blue'
    }, {
        id: '3',
        name: 'green'
    }];

    var colorId = 3;
    $scope.colorId = colorId;
    alert($scope.colorId);

    $scope.Select = function () {
        var colorId = 2;
        $scope.colorId = colorId;
    }
}

Here is a fiddle:

http://jsfiddle.net/ky5F4/23/

Answer

SoluableNonagon picture SoluableNonagon · Dec 4, 2014

you need to change the id to a string when doing Select

$scope.Select = function () {
    console.log('select fired');
    var colorId = 1;
    $scope.mySelection.colorId = colorId + "";
}

http://jsfiddle.net/bxkwfo0s/2/

next you should use a property of an object rather than just a scope variable, this will ensure proper model binding

ng-model="mySelection.colorId"

where the object could be something simple

$scope.mySelection = {colorId : colorId };