我是角度新手。我曾經有使用ng:repeat
填充的選擇框:使用angularjs中的選擇框(選定索引和默認選項)
<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',並懷疑它是有效的。如有必要糾正我。 – Sprottenwels
如果你搜索的話,有幾十個例子可以這樣使用它,並且它對我有效,雖然你是正確的,我找不到它的任何官方文檔。但是,這不是問題。如上所述,我不再使用該代碼;我正在使用「正確」的'ng-options',這就是問題開始的地方。 – EmmyS