1
我已經設置了一個plunker,基本上在下面的代碼中。 我無法在下拉列表中看到默認值[銀行帳戶號碼]被選中。我看到該模型正在更新。但由於某些原因,我的默認值沒有被選中。有人能幫我嗎?Angular:在下拉菜單中設置默認值
//index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="[email protected]" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js" data-semver="1.0.7"></script>
<script src="script.js"></script>
<script src="services.js"></script>
</head>
<body ng-controller="homeCtrl">
<h1>Other Criteria: {{ otherCriteria.optionText }}</h1>
<div>
<select data-ng-model="otherCriteria"
data-ng-options="o as o.optionText for o in criteria">
</select>
</div>
</body>
</html>
//services.js
app.factory("homeService", [
"$q",
function($q) {
function _getDropdownValues() {
var deferred = $q.defer();
var dropdownValues = [{"optionValue":"Bank_Account_Number","optionText":"Bank Account Number","selected":false},{"optionValue":"Bank_Security_Number","optionText":"Bank Security Number","selected":false},{"optionValue":"Cusip","optionText":"Cusip","selected":false},{"optionValue":"Transaction_Description","optionText":"Description","selected":false}];
deferred.resolve(dropdownValues);
return deferred.promise;
}
return {
getDropdownValues: _getDropdownValues
}
}
]);
//script.js
var app = angular.module("app", []);
app.controller("homeCtrl", function($scope, homeService) {
$scope.otherCriteria = {
optionValue: "Bank_Account_Number",
optionText: "Bank Account Number",
selected: false
};
homeService.getDropdownValues()
.then(function(dropdownValues) {
$scope.criteria = dropdownValues;
})
});
你也應該解釋爲什麼它更好 – sirrocco
@盧卡斯,你能解釋爲什麼它應該這樣做。如果我採用你的方法,那麼只有在加載$ scope.criteria之後,我才需要分配$ scope.otherCriteria。與我的plunker不同,我需要首先分配$ scope.otherCriteria,填充頁面中的其他部分,然後加載$ scope.criteria。 – user007
你可以在這裏找到更多的信息:http://gurustop.net/blog/2014/01/28/common-problems-and-solutions-when-using-select-elements-with-angular-js-ng-options-初始選擇/ 基本上: Angular.JS使用本地JavaScript比較來比較對象。在與Angular.JS無關的JavaScript中,比較對象(對象文字)是「通過引用」,因此它不會考慮對象的相似性。只檢查兩個引用比較指向內存中的同一個對象。 –