AngularJS - Empty option in select with ajax source

て烟熏妆下的殇ゞ 提交于 2019-12-25 07:49:48

问题


I have a select element that should be filled with some options that I need to retrieve from an API call, then set the first one as selected.

But Angular creates an empty option at first position and I don't know how to delete it.

Here's my code:

HTML

<select class="form-control" ng-model="selectedPositionFamily">
    <option ng-repeat="pf in positionFamilies" ng-value="pf.uuid">{{pf.name}}</option>
</select>

Controller

function Controller($scope, PositionFamilyService) {

    $scope.positionFamilies = [];

    $scope.selectedPositionFamily = "";

    initController();

    function initController() {

        PositionFamilyService.getAll({ 'sort' : 'order,asc' })
            .then(function(data){
                $scope.positionFamilies = data.content;
                $scope.selectedPositionFamily = $scope.positionFamilies[0].uuid;                        
            });
    }
}

回答1:


Same thing can be achieved using ng-options

html

<select ng-model="selectedPositionFamily" 
ng-options="pf.uuid as pf.name for pf in positionFamilies"></select>

js

$scope.positionFamilies = [{uuid:1, name:"val1"},
{uuid:2, name:"val2"},{uuid:3, name:"val3"}];
$scope.selectedPositionFamily = $scope.positionFamilies[0].uuid;

https://jsfiddle.net/mxno5esv/



来源:https://stackoverflow.com/questions/39778535/angularjs-empty-option-in-select-with-ajax-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!