[英]select ng-options not updating ng-model in AngularJS with ajax
我有一个简单的问题,我真的不知道我的逻辑中缺少什么。
在这个小提琴中工作得很好(不使用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 suggestion.Detail
。
好吧,经过更大的搜索,我设法解决并理解了我的错误。
首先,由于我的T-SQL背景,我不知道“文本”是sugestion的别名。表达式text as suggestion.Detail for suggestion in SuggestionList
中的detail字段text as suggestion.Detail for suggestion in SuggestionList
。SuggestationList text as suggestion.Detail for suggestion in SuggestionList
但事实并非如此! 这里的“文本”一词不是ALIAS,而是您希望AngularJS作为ng-model公开的object / object.field ...因此,这就是我的解决方案(列表中的对象为ng-模型)更新为: suggestion as suggestion.Detail for suggestion in SuggestionList
ng-options="suggestion as suggestion.Detail for suggestion in SuggestionList"
好的,这只是解决了WhoIsSelectedFirstApproach的问题,但是如果我想将对象传递给ng-change中的函数,请使用表达式中的suggestion
进行工作((不知道为什么他们对不同的ng- *使用不同的表达式逻辑)解决该问题的方法是,您可以在ng-change内引用ng-model字段:因此我可以按以下方式管理将Function(suggestion)
更改为Function(modelField)
:
ng-change="WhoIsSelected(SelectedSuggestion)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.