如何在angularjs中设置select的默认值

时间:2018-06-09 06:50:27

标签: javascript angularjs

我有这个:

  <select class=" text-center form-control" name="custname"
            ng-model="a.custid" 
            ng-init="devcustname[0].customer_name"
            ng-change="fetchassocd(a)">

     <option value="" selected="true">Please select a Customer name</option>
     <option ng-repeat="a in devcustname | orderBy:['customer_name']"
            value="{{a.customer_id}}">{{a.customer_name}}
    </option>
  </select>

我希望默认值为devcustname[0].customer_name。 ng-init无法正常工作。当devcustname[0].customer_name为空或未定义时,我想要&#34;请选择一个客户名称&#34;显示为默认值。

如果我使用ng-options,我无法显示&#34;请选择客户名称&#34;&#34;。

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
angular.module('app', []).controller('ctrl', function($scope){
   $scope.devcustname = [
    {customer_id: "3", customer_name: '', customer_email: "fas@gmail.com", contact_no: "23", address_line1: "6, f4"},
    {customer_id: "4", customer_name: "ab", customer_email: "sm", contact_no: "12", address_line1: "R V Road, 10th cross"},
    {customer_id: "5", customer_name: "da", customer_email: "3a@gmail.com", contact_no: "33", address_line1: "6, f4"}
  ];   
  $scope.a = {custid: "4"};
})
&#13;
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>
  <select class="text-center form-control" name="custname" ng-model="a.custid" ng-init="temp = devcustname[0].customer_name || (a = {custid:''})" ng-change="fetchassocd(a)">
    <option value="" ng-disabled="isDisabled">
    	-Please select a Customer name-
    </option>
    <option ng-repeat="a in devcustname | orderBy : 'customer_name'" value="{{a.customer_id}}">
      {{a.customer_name}}
    </option>
 </select>  
</div>
&#13;
&#13;
&#13;

相关问题