0

I am having troubles with setting the default value of a select box in HTML using AngularJS.

Here's my scope variable in the controller:

$scope.sensorReadingsPerPage = 30;

and here's the selection box in the view that's using the controller:

<select id="itemsPerPage" name="itemsPerPage" class="panel panel-default" ng-model="sensorReadingsPerPage" ng-change="changeItemsPerPage()">
  <option value="10">10</option>
  <option value="20">20</option>
  <option value="30">30</option>
  <option value="40">40</option>
  <option value="50">50</option>
  <option value="100">100</option>
</select>

I want the option with '30' value to be preselected.

I've tried using this answer and this one, both of them referencing AngularJS documentation on select directive, but in these cases the options are being dinamically generated AND the scope consists in an object with several values in it. In my case, the options are static and there's just a variable on the scope.

How can I go around this? Is there a way to change the ng-init and ng-options to fit my case?

Community
  • 1
  • 1
Ernani
  • 319
  • 1
  • 4
  • 18

2 Answers2

1

Try setting $scope.sensorReadingsPerPage = "30" in your controller.

Note: It should be a string.

Nikhil Bhandari
  • 1,584
  • 2
  • 16
  • 34
  • 1
    This answer is more useful since it shows a very simple solution and that I was wrong in trying to set ng-model as a Integer value. I didn't know it had to be a String. – Ernani Mar 24 '17 at 13:18
1

Have you tried using ng-options instead of creating separate option elements?

<select id="itemsPerPage" name="itemsPerPage" class="panel panel-default" ng-options="item in items track by $index" ng-model="sensorReadingsPerPage" ng-change="changeItemsPerPage()">

And in your controller

$scope.items = [10, 20, 30, 40, 50, 100];
$scope.sensorReadingsPerPage = $scope.items[2];
AJ Funk
  • 3,099
  • 1
  • 16
  • 18
  • I tried this answer and it worked as well, but it required more aggressive changes in my code. – Ernani Mar 24 '17 at 13:40