选择ng-options不使用ajax更新AngularJS中的ng-model

时间:2015-12-03 13:34:58

标签: javascript angularjs ajax autocomplete

我有一个简单的问题,我真的不知道我的逻辑中缺少什么。

在这个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 ?!?!?
  }
})

2 个答案:

答案 0 :(得分:1)

在你的ng选项中,它应该是suggestion.Detail as text而不是text as suggestion.Detail

答案 1 :(得分:0)

好吧,经过更大规模的搜索,我设法解决并理解我的错误。

首先,由于我的T-SQL背景,我明白“text”是表达式text as suggestion.Detail for suggestion in SuggestionList中sugestion.Detail字段的别名,但事实并非如此! 这里的“text”这个词不是ALIAS,它是你希望AngularJS公开的对象/对象。字段作为ng-model ...所以,那就是说,我的情况下的解决方案(列表中的对象为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)"

SOLVED JS FIDDLE