2015-12-31 82 views
-1

我有一個下拉使用angularjs,但在初始加載它顯示'沒有選擇',我想選擇第一個值默認。angularjs下拉顯示沒有選擇時加載第一次

<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> 
+0

我想這篇文章可以幫助你:[這裏](http://stackoverflow.com/questions/18194255/how-to-have-a-default-option -in-select-box-angular-js) 你必須使用ng-init –

回答

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>

相關問題