【发布时间】:2014-03-19 16:36:02
【问题描述】:
我是 Angular 的新手。我曾经有一个使用ng:repeat 填充的选择框:
<select ng-model="selectedAddress" ng-change="handleStoredAddressClick2()" id="address_dropdown">
<option value="-1" selected="selected">Add a new address</option>
<option ng:repeat="stored_address in address_dropdown" value="{{$index}}">{{stored_address.dropdown_display}}</option>
</select>
它生成的 HTML 如下所示:
<select id="address_dropdown" ng-change="handleStoredAddressClick2()" ng-model="selectedAddress" class="ng-pristine ng-valid">
<option value="? undefined:undefined ?"></option>
<option selected="selected" value="-1">Add a new address</option>
<option value="0" ng:repeat="stored_address in address_dropdown" class="ng-scope ng-binding">602 BLOWING ROCK RD APT. 2 BOONE, NC 28607</option>
<option value="1" ng:repeat="stored_address in address_dropdown" class="ng-scope ng-binding">TEST HOUSE: 9884 BLUEBONNET BLVD BATON ROUGE, LA 70810</option>
</select>
我有一个在ng-click 上运行的函数:
$scope.handleStoredAddressClick2 = function () {
var address = $scope.address_dropdown[$scope.selectedAddress];
$scope.streetaddr = address.address
$scope.search_near = address.zip;
var disp_addr = address.address;
if (address.address_two) {
disp_addr += ', ' + address.address_two;
}
if (typeof disp_addr != 'undefined' && disp_addr.toTitleCase) {
disp_addr = disp_addr.toTitleCase();
}
$scope.streetaddr = disp_addr;
$scope.stored_addr_key = address.key;
$scope.cityname = address.city;
$scope.statename = address.state;
$scope.fetch();
};
函数的第二行获取了在ng:repeat value 属性中设置的{{$index}} 值。 (因此,在这种情况下为 0 或 1。)
最近有人告诉我,您不应该使用ng:repeat 来填充选择框;你应该改用ng-options。所以我将我的选择框更新为:
<select ng-model="selectedAddress" ng-init="selectedAddress = selectedAddress || address_dropdown[0].value" ng-change="handleStoredAddressClick2()" ng-options="a.dropdown_display for a in address_dropdown" id="address_dropdown">
<option value="-1" ng-selected="selected">Add a new address</option>
</select>
这是生成的 HTML:
<select id="address_dropdown" ng-options="a.dropdown_display for a in address_dropdown" ng-change="handleStoredAddressClick2()" ng-model="selectedAddress" class="ng-pristine ng-valid">
<option value="?" selected="selected"></option>
<option value="0">602 BLOWING ROCK RD APT. 2 BOONE, NC 28607</option>
<option value="1">TEST HOUSE: 9884 BLUEBONNET BLVD BATON ROUGE, LA 70810</option>
</select>
本质上是一样的,尤其是选项值。但是我现在在更改时遇到错误,说address is undefined。因此,出于某种原因,$scope.address_dropdown[$scope.selectedAddress]; 不再用于在更改时获取下拉列表的选定索引值,即使无论代码如何生成,实际索引值都是相同的。
谁能解释为什么会这样,以及如何获取填充有ng-options 的选择框的选定索引值?我是否还可以回答为什么我在第二组代码(下面重复)中设置的默认选定选项的文本最终显示为空白?
代码: 添加新地址
渲染:
【问题讨论】:
-
我从未在您的标记中看到这种冒号语法
ng:repeat,并且怀疑它是否有效。如有必要,请纠正我。 -
如果您搜索 SO,那么有几十个使用这种方式的示例,它确实对我有用,尽管您是正确的,因为我找不到任何官方文档。然而,这不是问题。如前所述,我不再使用该代码;我正在使用“正确的”
ng-options,这就是问题开始的地方。
标签: angularjs ng-options