Search code examples
angularjsselectng-options

Angularjs: Select ng-options right way


For the select tag with angularjs i'm doing:

<select ng-init="getdata()" data-ng-model="ob.id" 
        data-ng-options="level.id as level.desc for level in levels" 
        data-ng-selected="ob.id == level.id"> 
        <option value="0">default...</option>
</select>

... but is this the right way because there are so many other ways on the web? getdata() gets $scope.levels array.


Solution

  • You don't need to write ng-selected, it's not necessary. Also ng-init should just be used in really specific cases (nginit) so as OZ mentioned it'd better to call getData() from the controller.

    <select data-ng-model="ob.id" 
            data-ng-options="level.id as level.desc for level in levels"> 
        <option value="0">default...</option>
    </select>
    

    Other than that the select looks correct.