Nobody
Nobody

Reputation: 83

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

Upvotes: 0

Views: 66

Answers (1)

Slava Utesinov
Slava Utesinov

Reputation: 13498

angular.module('app', []).controller('ctrl', function($scope){
   $scope.devcustname = [
    {customer_id: "3", customer_name: '', customer_email: "[email protected]", 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: "[email protected]", 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>

Upvotes: 1

Related Questions