我有一个简单的问题,我真的不知道我的逻辑中遗漏了什么。
在这个示例中,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 ?!?!?
}
})发布于 2015-12-03 21:54:00
在您的ng选项中,应该是suggestion.Detail as text而不是text as suggestion.Detail。
发布于 2015-12-03 22:14:59
嗯,在更大的搜索之后,我设法解决了问题,也理解了我的错误。
首先,由于我的T-SQL背景,我不明白“sugestion.Detail”是expression text as suggestion.Detail for suggestion in SuggestionList中文本字段的别名,但事实并非如此!这里的“文本”一词不是别名,它是你希望AngularJS公开为ng模型的对象/对象字段……因此,我的示例中的解决方案(列表中的对象为ng-model)更新为: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)"https://stackoverflow.com/questions/34067444
复制相似问题