gpt4 book ai didi

javascript - 在 ng-model 之后填充 ng-options

转载 作者:行者123 更新时间:2023-11-28 19:15:26 24 4
gpt4 key购买 nike

使用最新稳定的 AngularJS (1.3.15),填充 ng-options<select> ng-model之后已填充,看来该模型尚未选择。

HTML:

  <body ng-controller="MainCtrl">
Selected: {{selected}}
<br/>
<select ng-model="selected" ng-options="item as item for item in list">
<option value="">-- Select something --</option>
</select>
<span ng-show="loading">(loading...)</span>
</body>

JavaScript:

app.controller('MainCtrl', function($scope, $timeout) {
$scope.selected = 'first';
$scope.list = [];
$scope.loading = true;
$timeout(function () {
$scope.list = ["first","second","third"];
$scope.loading = false;
}, 1000);
});

Or Plunker with both.

如果list使用 $timeout() 填充为了模拟延迟加载,<option>元素已更新,但 ng-model 中的值未选择(我希望选择值 first)。这是一个错误还是我做错了什么?

最佳答案

您应该使用ng-options="item for item in list track by $index",然后在ajax加载后设置选定的值$scope.selected = first

  <body ng-controller="MainCtrl">
Selected: {{selected}}
<br/>
<select ng-model="selected" ng-options="item for item in list track by $index">
</select>
<span ng-show="loading">(loading...)</span>
</body>

注意

Using tack by $index will fix your problem, though select is not compatible with select

Working Plunkr

关于javascript - 在 ng-model 之后填充 ng-options,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29968735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com