Nimantha Harshana Perera Nimantha Harshana Perera - 4 days ago 5
AngularJS Question

AngularJS Select Box Set Default Selected Value on Document Ready

I have a weird problem when setting the model value of a dropdown on Document ready event. I want Option4 to be selected on page load, However this doesn't seems to be reflected on my view when I do things as follows. Please see below code...

HTML

<select ng-model="search_for" class="form-control" id="search_for">
<option value="">-Search For-</option>
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
<option value="4">Option4</option>
</select>


JS

angular.element(document).ready(function () {
$scope.search_for = 1;
}


Even when I do {{search_for}} in html it proves that model value is not set by showing nothing, but shows the value when dropdown value is changed.

What am I doing wrong ?.

Thank You.

Answer

Instead of adding it on document.ready add at the starting in the controller, since the controller loads prior to view, the model value gets reflected

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model="search_for" class="form-control" id="search_for">
                    <option value="">-Search For-</option>
                    <option value="1">Option1</option>
                    <option value="2">Option2</option>
                    <option value="3">Option3</option>
                    <option value="4">Option4</option>
</select> 

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.search_for = "2";
    
});
</script>

</body>
</html>

Please run the above snippet

Here is a working Demo

Comments