我有一个简单的问题,我真的不知道我的逻辑中缺少什么。
在此Fiddle工作正常(不使用 ajax/timeout),但我想了解并修复为什么当我使用 timeout/ajax 应用相同的逻辑时不会发生以下行为!!
这是我的简单示例:JS FIDDLE
HTML:
<body data-ng-app="appMain">
<div ng-controller="SearchController">
<input type="text" ng-model="SearchTerm" />
<input type="button" value="Submit Search" ng-click="QuerySuggestions()" />
<select ng-show="ShowSuggestion" name="cmbSelectedSuggestion" ng-model="SelectedSuggestion" ng-options="text as suggestion.Detail for suggestion in SuggestionList" ng-change="WhoIsSelected(suggestion)">
</select>
</div>
</body>
AngularJS:
angular.module('appMain',[])
.controller('SearchController',function($scope, $http, $timeout){
$scope.SearchTerm = '';
$scope.ShowSuggestion = false;
$scope.SuggestionList = [];
$scope.SelectedSuggestion = null;
$scope.QuerySuggestions = function()
{
//Simulating an AJAX that my response happens 2s afterwards
$timeout(function(){
var oJSON = {"List": [
{
"Id": 1,
"Type": "State",
"Name": "Rio de Janeiro",
"Detail": "Rio de Janeiro - State, Brazil"
}
,
{
"Id": 1,
"Type": "City",
"Name": "Rio de Janeiro",
"Detail": "Rio de Janeiro - City, Rio de Janeiro, Brazil"
}]};
$scope.SuggestionList = oJSON.List
$scope.ShowSuggestion = true;
}, 2000);
}
$scope.WhoIsSelected = function($option){
$scope.WhoIsSelectedFirstApproach();
$scope.WhoIsSelectedSecondApproach($option);
}
$scope.WhoIsSelectedFirstApproach = function(){
console.log($scope.SelectedSuggestion); //why undefined !?!?!
}
$scope.WhoIsSelectedSecondApproach = function($option){
console.log($option) //why undefined ?!?!?
}
})
最佳答案
在您的 ng-options 中,它应该是 suggestion.Detail as text
而不是 text as suggest.Detail
。
关于javascript - 选择 ng-options 不使用 ajax 更新 AngularJS 中的 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34067444/