Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Select Not Binding To Ng-Model

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/

like image 808
Jeremy Wagner Avatar asked Jan 10 '23 08:01

Jeremy Wagner


1 Answers

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 };
like image 121
SoluableNonagon Avatar answered Jan 21 '23 09:01

SoluableNonagon