Search code examples
javascriptangularjsangularjs-ng-repeathtml-select

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


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>