3

I have looked at so many examples as to how to do this, but still can't seem to figure it out. I have setup a very simple angular app with controller and am trying to populate a single select tag.

<body data-ng-app="App">
<div data-ng-controller="DemoController">
    {{var}}
    <select data-ng-options="v.id as v.name for v in selectVals">
        <option value="">Select</option>
    </select>
</div>
</body>

angular.module('App', []).controller('DemoController', function($scope) {
        $scope.var = 'a';
        $scope.selectVals = [
            { name: '1st', id: 1 }, 
            { name: '2nd', id: 2 }
        ];
});

Here is the jsFiddle: http://jsfiddle.net/Fc5ne/3/ Any help would be greatly appreciated.

I already looked in these places and tried to compare my code, but am still missing something: https://docs.angularjs.org/api/ng/directive/select, http://jsfiddle.net/qWzTb/, http://jsfiddle.net/qm7E7/19/, Angular: Binding objects to <select>, ... as well as a few other stack overflow questions.

2 Answers 2

6

This is a tricky one. The ng-model directive is required as well. Rest assured that many other people (including myself) have been burnt by this.

<select data-ng-model="test" data-ng-options="v as v.name for v in selectVals"></select>

http://jsfiddle.net/Fc5ne/4/

1
1

For setting up the options of the select element, one can use ng-options directive. For the selected value, one can use ng-model directive.

jsfiddle: http://jsfiddle.net/rpaul/j5ewuek5/

Not the answer you're looking for? Browse other questions tagged or ask your own question.