初始化' - 选择 - '在下拉列表中

时间:2017-08-15 09:58:29

标签: html angularjs

当我使用ng-options从服务器获取选择选项时,如何初始化 - 选择 - 作为第一个选项..我已经尝试过ng-init但它没有锻炼..

  

html元素

<select   ng-options="item as item.approver1_name for item in request.approver1_data track by item.id" id="selectform" ng-model="selected_approver1_email"  >

我可以获取批准者列表。但我需要添加--select--选项作为默认值..

2 个答案:

答案 0 :(得分:1)

你可以这样做

HTML

<div ng-controller="MyCtrl">
    <select ng-options="region.code as region.name for region in regions" ng-model="region">
    <option style="display:none" value="">--select--</option>
    </select>
    <br>selected: {{region}}
</div>

控制器

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.regions = [
        {
        name: "Alabama",
        code: "AL"},
    {
        name: "Alaska",
        code: "AK"},
    {
        name: "American Samoa",
        code: "AS"},
        ];
}

以下是工作JSFIDDLE的链接,您可以在其中进行进一步的实验。

答案 1 :(得分:0)

您可以使用ng-init设置默认值,只需将默认对象附加到数组

即可
$scope.approver1_data.push({
        id: '-1',
        name: '--Select--'
    });

<强>样本

&#13;
&#13;
angular.module('ngrepeatSelect', [])
    .controller('ExampleController', ['$scope', function ($scope) {
    $scope.approver1_data  = [ {
        id: '1',
        name: 'Option A'
    }, {
        id: '2',
        name: 'Option B'
    }, {
        id: '3',
        name: 'Option C'
    }];
    $scope.approver1_data.push({
        id: '-1',
        name: '--Select--'
    });
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ngrepeatSelect">
    <div ng-controller="ExampleController">
        <form name="myForm">
            <label for="repeatSelect">Angular select:</label>
<select name="repeatSelect" 
   id="repeatSelect" 
   ng-model="repeatSelect"
   ng-init=" repeatSelect = '-1'"  
   ng-options="option.id as option.name for option in approver1_data">          
</select>
        </form>
        <br/> <tt>Selected value: {{repeatSelect}}</tt>

    </div>
</div>
<br/>
&#13;
&#13;
&#13;