3

I have this very simple select element:

<label>Items per page</label>
    <select class="form-control input-sm w25" ng-model="itemsPerPage">
        <option value="5">5</option>
        <option value="10">10</option>
        <option value="25">25</option>
        <option value="50">50</option>
    </select>

with controller:

 $scope.itemsPerPage = 5; // default value

But the default value is a blank option and the default value attempt doesn't do anything.

How do I make the value 5 the default?

Ignacio Ara
  • 2,476
  • 2
  • 26
  • 37

2 Answers2

2

Angular is probably converting that value to a string, so do:

$scope.itemsPerPage = "5";
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

The blank option appears because ng-model can't find an option that matches the value of the bound property (option values are converted to string and the bound property is number).

If you don't want to change the type of your itemsPerPage property and make it a string, you can keep a number and define, in your $scope, an object with a getter and setter that will take care of the type conversion.

angular.module('dummyApp', [])
  .controller('DummyController', function($scope) {

    var itemsPerPage = 5; // still a number
    Object.defineProperty($scope, "itemsPerPage", {
      get: function() {
        return itemsPerPage + "";
      },
      set: function(newValue) {
        itemsPerPage = parseInt(newValue);
      }
    });
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.js"></script>
<div ng-app="dummyApp" ng-controller="DummyController">
  <label>Items per page</label>
  <select class="form-control input-sm w25" ng-model="itemsPerPage">
    <option value="5">5</option>
    <option value="10">10</option>
    <option value="25">25</option>
    <option value="50">50</option>
  </select>
</div>
Guillaume Georges
  • 3,878
  • 3
  • 14
  • 32