简体   繁体   中英

How to set default value for select in angularjs

I have this:

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

I want the default value to be devcustname[0].customer_name . The ng-init is not working. When the devcustname[0].customer_name is null or undefined I want the "Please select a Customer name" to be displayed as default.

If I use ng-options I can't show the "Please select a Customer name"".

 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: "RV 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"}; }) 
 <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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM