Set default value for dropdownlist using angularjs?

I have code that populates then dropdownlist and the javascript variable that gets the last item in the list. Now all I want to do is select that last item as the default .What am I missing ?

<div class="row">
<div>
    <select ng-init="lastItem" ng-model="congressFilter" ng-options="cc.congressLongName for cc in ccList"></select>
</div>
<div class="grid-style" data-ng-grid="userGrid">
</div>

   ccResource.query(function (data) {
    $scope.ccList.length = 0;
    angular.forEach(data, function (ccData) {
        $scope.ccList.push(ccData);
    })

    //Set default value for dropdownlist?
    $scope.lastItem = $scope.ccList[$scope.ccList.length - 1];
});

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You simply need to asign a value to congressFilter in your controller.

 $scope.congressFilter = 'someVal';

It depends a little on how your data looks however.

Solution 2

It might help to new developers. need to add default id for display default item in option.

The below code sample we add [ $scope.country.stateid = “4” ] in controller $scope to set the default.

    var aap = angular.module("myApp", []);

    aap.controller("MyContl", function($scope) {
      $scope.country = {};
      $scope.country.stateid = "4";

      $scope.country.states = [{
        id: "1",
        name: "UP"
      }, {
        id: "4",
        name: "Delhi"
      }];
    });

<body ng-app="myApp">
  <div ng-controller="MyContl">
    <div>
      <select ng-model="country.stateid" ng-options="st.id as st.name for st in country.states">
      </select>
     ID :  {{country.stateid}}
    </div>
  </div>
</body>

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply