1

我使用 angular.js (ng-model="searchText") 创建了一个可通过输入进行搜索的列表。单击列表元素时,您可以使用 {{selected | 提取所选项目的内容 json}}。单击列表项时,我想将此选定元素用作输入的值。

我本质上想创建自己的自动完成功能,它始终显示选项列表,在键入时过滤选项,并在单击选项时填写输入。

HTML

<html ng-app> 
<section>
   <div id="content-body" class="container search-page"><!-- begin content-body -->
    <div id="content-frame" class="container"></div><!-- end content-frame -->
      <section>
        <div class="search-container">
          <div class="search-wrapper">
            <input type="search" class="input-from" autocomplete="off" placeholder="Search" ng-model="searchText" value="{{searchText}}">
          </div> 
        </div>
      </section>
      <section>
        <div ng-controller="ContentCtrl">
          <ul class="list-group search">
        <!--<li class="list-group-item group-title">
                <span class="icon itinerary-icon"></span>
                Popular Destinations
            </li>-->
              <a ng-click="setMaster(cities)" ng-repeat="city in cities | filter:searchText | limitTo:limit" href="#" class="list-group-item">{{city}}</a>
          </ul>
        </div>
      </section>
   </div><!-- end content-body -->
</html>    

JS

function ContentCtrl($scope, $http) {
    "use strict";

    $scope.url = '../mobile-site/cities.json';
    $scope.cities = [];
    $scope.limit = 10; // max 10 cities loaded

    $scope.fetchContent = function() {
        $http.get($scope.url).then(function(response){
            $scope.cities = response.data.cities; 
        });
    }

    $scope.fetchContent(); // build cities list

    $scope.setMaster = function(city) {
            $scope.searchText = city; // pull selected city using {{selected | json}}
        }
    } 

JSON

{
"version": "082B6AF45261B81358E8F99F0FAEC4A4",
"cities": [
"A Friela Maside, Spain",
"A Gudina, Spain",
"AHA, Germany",
"AL, Norway"
]
}
4

1 回答 1

3

我认为您在代码中有一些错误:

<div ng-model="chosen">
    <a ng-click="setMaster(cities)" ng-repeat="cities in cities | filter:searchText | limitTo:limit" href="#" class="list-group-item">{{cities}}</a>
</div>

应该是

<div ng-repeat="city in cities | filter:searchText | limitTo:limit">
    <a ng-click="setMaster(city)" class="list-group-item">{{city}}</a>
</div>

那我想你想要的是

$scope.setMaster = function(city) {
    $scope.searchText = city;
}

另外,我不确定 div 上的 ng-model 是做什么用的,据我所知,它仅用于输入、文本区域和选择。请参阅http://docs.angularjs.org/api/ng.directive:ngModel

你可能想要这样的小提琴 -> http://jsfiddle.net/weSpW/3/

于 2013-04-15T19:37:04.600 回答