【问题标题】:Get all options from select box when options are o=constructed using ng-repeat当使用 ng-repeat 构造选项时,从选择框中获取所有选项
【发布时间】:2019-02-18 10:22:26
【问题描述】:

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

正如你在运行 sn -p 时看到的那样,找到的项目返回为“0”。

但如果您手动构建选项,则以下 sn-p 有效。

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 一起使用时如何获取所有选项。谢谢!

【问题讨论】:

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


    【解决方案1】:

    这是因为您的函数在 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>

    【讨论】:

    • 天哪!我怎么没想到。非常感谢!
    • @Mona 很乐意为您提供帮助 :-)
    • 你也可以这样做:var x = $('#mySelect').options.length; $('#mySelect').html("Found " + x + " options in the list.");
    猜你喜欢
    • 2016-08-20
    • 1970-01-01
    • 2015-05-14
    • 2014-06-21
    • 2015-11-26
    • 1970-01-01
    • 2018-02-12
    • 2015-07-09
    • 1970-01-01
    相关资源
    最近更新 更多