当选项使用ng-repeat进行o ==构造时,从选择框中获取所有选项

时间:2018-09-13 16:16:00

标签: javascript angularjs select angularjs-ng-repeat options

我正在尝试从下拉列表中检索所有选项。手动构造它们时,我会得到所有选项,但是使用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>

如您所见,在运行代码段时,发现的项目将返回为“ 0”。

但是,如果您手动构造选项,则以下代码片段可以正常工作。

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>

想知道ng-repeat与select一起使用时如何获得所有选项。谢谢!

1 个答案:

答案 0 :(得分:0)

之所以发生,是因为您的函数在呈现DOM之前就已执行。只需将您的代码包装在$timeout中,它就会按预期工作,因为$timeout仅在呈现DOM后才会执行您的代码。

工作示例:

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>