Get all options from select box when options are o=constructed using ng-repeat

Issue

I am trying to retrieve all the options from the dropdown list. I get all the options when they are manually constructed but I can’t get them when constructed using ng-repeat.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
    
     var x = document.getElementById("mySelect").options.length;
    document.getElementById("demo").innerHTML = "Found " + x + " options in the list.";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<p id="demo"></p>

<select id="mySelect" >
<option ng-repeat="x in names">{{x}}</option>
</select>


</div>

As you see when you run the snippet items found is returned as “0”.

But the below snippet works if you construct options manually.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
    
     var x = document.getElementById("mySelect").options.length;
    document.getElementById("demo").innerHTML = "Found " + x + " options in the list.";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<p id="demo"></p>

<select id="mySelect" >
<option >Emil</option>
<option >Tobias</option>
<option >Linus</option>
</select>


</div>

Would like to know how to get all the options when ng-repeat it used with select. Thanks!

Solution

It is happening because your function executes before the DOM is rendered. Simply wrap your code inside $timeout and it will work as expected, as $timeout will execute your code only after DOM is rendered.

Working Example:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
    $scope.names = ["Emil", "Tobias", "Linus"];
    $timeout(function () {
        var x = document.getElementById("mySelect").options.length;
        document.getElementById("demo").innerHTML = "Found " + x + " options in the list.";
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<p id="demo"></p>

<select id="mySelect" >
<option ng-repeat="x in names">{{x}}</option>
</select>


</div>

Answered By – amrender singh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published