angularjs下拉显示第一次加载时未选择任何内容

时间:2015-12-31 08:55:36

标签: angularjs

我使用angularjs下拉,但在初始加载时显示“没有选择”,我想选择First value default。

<select id="cbo-db-selection" ng-init="selectedlibrary=selectedlibrary[0].value" ng-model="selectedlibrary" required="required" ng-options="opt.DatabaseName as opt.DatabaseName for opt in DBLibraries">
  <option style="display:none" value="">{{selectedlibrary}}</option>
</select>

1 个答案:

答案 0 :(得分:1)

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
    $scope.users = [
        {id: 1, name: 'Me'},
        {id: 2, name: 'You'}
    ];
});

app.directive('select', function () {
    return {
        restrict: 'E',
        require: '?ngModel',
        priority: 10,
        link: function postLink(scope, elem, attrs, ctrl) {
            if (!ctrl) { return; }
            var originalRender = ctrl.$render.bind(ctrl);
            ctrl.$render = function () {
                originalRender();
                if (elem.val() === '?') {
                    ctrl.$setViewValue(undefined);
                }
            };
        }
    };
});
.error {
    color: Red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl" ng-form="form1">

  <select ng-model="userId">
    <option ng-repeat="user in users"
            value="{{user.id}}">
      {{user.name}}
    </option>
</select>
  
    
    <div class="error" ng-show="form1.select1.$invalid">Required field !</div>
    <div class="error" ng-show="form1.$invalid">Invalid form !</div>
    <br />
    <button ng-click="userId=1;">Set valid value</button>
    <button ng-click="userId=3;">Set invalid value</button>
    <hr />
    <pre>userId: {{userId}}</pre>
</div>