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?

2 Answers 2

1

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

Note: It should be a string.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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];

1 Comment

I tried this answer and it worked as well, but it required more aggressive changes in my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.