NomaD
NomaD

Reputation: 111

AngularJS - how to set default select option

I am using AngularJS to render my page. I need to have 2 selectors with the same data, so I use a controller. Data should by received by GET request, and I want to add an extra option which is selected by default. I have already tried to add this by concatenating response with option like {id:-1, name:"All"}.concat($scope.dfleets), but the attempt failed. It is clear that option should be added inside html. The code below creates an appropriate select list, but selectCtrl.selectedValue = selectCtrl.defaultValue.id seems to have no effect, and no item is selected on page load.

html page

<div ng-controller="SelectController as selectCtrl">
<select ng-model="selectCtrl.selectedValue" class="form-control" id="selectFleet_1" ng-init="showDriversFleets()">
    <option value="selectCtrl.defaultValue.id">{[{selectCtrl.defaultValue.name}]}</option>
    <option ng-repeat="value in selectCtrl.values" value="{[{value.id}]}">{[{value.name}]}</option>
</select>

js code

dApp.controller('SelectController', ['$scope', '$http', function ($scope, $http){

$scope.showDriversFleets = function() {
    $scope.dfleets = [];

    $http.get('/api/driver/fleets/').then(function (res) {
        return angular.forEach(res.data, function (item) {
            return $scope.dfleets.push(item);
        });
    });
}

var selectCtrl = this;
selectCtrl.defaultValue = {id:-1, name:"All"}
selectCtrl.values = $scope.dfleets;
selectCtrl.selectedValue = selectCtrl.defaultValue.id;
}]);

Upvotes: 0

Views: 929

Answers (2)

Tom22
Tom22

Reputation: 508

Here is a plunker demonstration of two ways that could work https://plnkr.co/edit/xx8ZjBdy55sgyIYdcNAw?p=preview

I have the more complicated method first which would let you customize the select drop downs more.

I imagine it should be in a separate directive. It required more maneuvering in the controller than I think is good form.

I'm certainly not an expert - not necessarily sure about best practices

The second version I include comes closer to what was in their documentation so perhaps you should use that method.

<html ng-app="selectListNgDefault">
<head>
  <title>Check-box to toggle list</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js">     </script>
  <script src="selectListAngularSO.js"></script>
  <style type="text/css" media="screen">
    .left{ background-color: pink; width: 250px; height: 150px; display: inline-block; float: left;}
    .right{ background-color: beige; width: 250px; height: 150px; display: inline-block; float: left;}
    .demonstration{display:inline-block; border: 1px solid black; clear: both;}
    .processing-message{width: 500px; background-color: yellow; display:inline-block; border: 1px solid black; clear: both;}
  </style>
 </head>

<body ng-controller="defaultAllSelectListCtrl" ng-init="checkedList=true">
  <div class="demonstration">
    <div class="left">
      <h3>Using ng-repeat for selection</h3>
      <label >Select a Fleet</label>
      <select ng-init="selectedFleet=dfleets[0].id" ng-model="selectedFleet" ng-change="handleFleetSelectionFromString(selectedFleet)">
        <option ng-repeat="fleet in dfleets" value="{{fleet.id}}" >{{fleet.brand}}({{fleet.cars}})</option>
      </select>

      <p>There are {{dfleets.length - 1}} fleet brands</p>
      </div>
    <div class="right">
      <h1><em>{{selectedFleetFromId.brand}}</em> Drivers</h1>
      <h2>Have {{selectedFleetFromId.cars}} cars!</h2>
    </div> 
  </div>

  <div class="demonstration">
    <div class="left">
      <h3>Using ng-options for selection</h3>
      <label >Select a Fleet</label>
      <select ng-init="ngOptionsSelectedFleet=dfleets[0]" ng-model="ngOptionsSelectedFleet" ng-options="v.brand for (k,v) in dfleets" ng-change="handleFleetSelection(ngOptionsSelectedFleet)"></select>
    </div>
    <div class="right">
      <h1>{{ngOptionsSelectedFleet.brand}} Drivers</h1>
      <h2>Have {{ngOptionsSelectedFleet.cars}} cars!</h2>
    </div> 
  </div>
  <br>
  <div ng-hide="hideProcessingMessage"  class="processing-message">
    Alert: {{processingMessage}}
  </div>
</body>
</html>

And below is the js file

var app = angular.module('selectListNgDefault', []) ;


  app.controller('defaultAllSelectListCtrl', function ($scope, $http) {
    var dummyData = [{id: "id1", brand: "Ford", cars: 12},{ id: "id2", brand: "Volkswagen", cars: 11},{id: 'id3', brand: "Mercedes", cars: 6},{id:"id4", brand: "Toyota", cars: 2},{id: "id5", brand: "Honda", cars: 19}];
    $scope.hideProcessingMessage = true;

    $scope.showDriversFleets = function() {
      // $http.get('/api/driver/fleets/').then(function (res) {
      //     return angular.forEach(res.data, function (item) {
      //         return $scope.dfleets.push(item);
      //     });
      // });
      $scope.dfleets = [];
      let totalCars = 0;
      dummyData.forEach(function(fleet){
        $scope.dfleets.push(fleet);
        totalCars+= fleet.cars;
      });
      //alphabetize first?
      $scope.dfleets.sort(function(a,b){return (a.brand < b.brand ) ?  -1 :  1;});
      //insert your custom default to appear giving it an arbitrary id?
      $scope.dfleets.unshift({id: "idAll", brand: "All Fleets'", cars: totalCars});
      // initialize display if you're using more detailed ng-repeat approach
     $scope.selectedFleetFromId = {id: "idAll", brand: "All Fleets'", cars: totalCars}
    };

    $scope.handleFleetSelection = function(fleet){
      $scope.hideProcessingMessage=false;
      $scope.processingMessage = "Congratulations, your " + fleet.brand + " representative will contact you soon";
    }

    $scope.handleFleetSelectionFromString = function(fleetIdString){
      $scope.selectedFleetFromId = $scope.dfleets.find( (fleet) => fleetIdString === fleet.id );
      $scope.hideProcessingMessage=false;
      $scope.processingMessage = "Congratulations, your " +    $scope.selectedFleetFromId.brand + " representative will contact you soon";
    }


    $scope.showDriversFleets();


})

I hope my ideas help you get a bit further even if they're not perfect. : )

This prior SO post discusses use of a select box with angular... not exactly your default question but worth looking at. how to use ng-option to set default value of select element

Upvotes: 1

Sumit Deshpande
Sumit Deshpande

Reputation: 2155

Use ng-options and add an empty default value option inside select element as -

<select ng-options="...">
     <option value="">Select Value</option>
</select> 

OR

If you want to select option within assigned collection then -
Plunker - https://plnkr.co/edit/ApMlLTLOXfJKKutcEuFW?p=preview

angular.module('app', [])
  .controller('ctrl', function($scope, $http) {
    var urlBase = 'countries.json';
    $scope.register = {};
    $scope.register.countryId = "-1";
    $scope.register.countries = [];
    $scope.showDriversFleets = function() {
      $http.get(urlBase).success(CreateCountryList);
    }

    function CreateCountryList(res) {
      angular.forEach(res, function(item) {
        $scope.register.countries.push(item);
      });
      $scope.register.countries.insert(0, {
        "id": "-1",
        "name": "Select Country"
      });
    }

    Array.prototype.insert = function(index, item) {
      this.splice(index, 0, item);
    };
  })

Upvotes: 1

Related Questions