Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular js select binding

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.

like image 503
peinearydevelopment Avatar asked Aug 25 '26 19:08

peinearydevelopment


2 Answers

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/

like image 165
David East Avatar answered Aug 28 '26 08:08

David East


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/

like image 32
Razan Paul Avatar answered Aug 28 '26 08:08

Razan Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!