带有文本输入的AngularJS搜索列表,单击列表项应相应地更新文本框并隐藏列表

时间:2019-03-07 16:02:49

标签: javascript html angularjs forms

我仍在与AngularJS交涉,无法找到与我的问题类似的东西。基本上,我使用文本框过滤站点名称列表,并且每个列表项都显示为按钮。

用户单击按钮时,应使用该值更新文本框,并再次隐藏列表。我尝试在按钮上使用“ ng-click”并定位输入框,但是尽管没有错误,但无法使其正常工作。任何帮助将不胜感激,或建议,如果我完全走错了方向。非常感谢:)

HTML

<div ng-app="myApp" ng-controller="searchCtrl">
  <input type="text" ng-model="txtSearch" placeholder="From" id="one">
    <ul>
      <li ng-if="txtSearch" ng-repeat="test in List1 | filter:txtSearch track by test.id">
      <button>{{ test.name }}</button>
      </li>
    </ul>

<hr>

    <input type="text" ng-model="txtSearch2" ng-change="CallSearch(txtSearch2)" placeholder="To">
    <ul>
      <li ng-repeat="test in List2 track by test.id">
      <button>{{ test.name }}</button>
      </li>
    </ul>
</div>

JS

var app = angular.module('myApp', []);

app.controller('searchCtrl', function($scope) {
  $scope.List1 = [
    {id: 1, name: 'Uxbridge'},
    {id: 2, name: 'West Drayton'},
    {id: 3, name: 'Hayes'},
    {id: 4, name: 'Hillingdon'},
    {id: 5, name: 'Ealing'},
    {id: 6, name: 'Southall'},
    {id: 7, name: 'Harrow'},
    {id: 8, name: 'Eastcote'},
    {id: 9, name: 'Ruislip'},
    {id: 10, name: 'Hounslow'}
  ];

  $scope.CallSearch = function(textSearch) {console.log(textSearch.length);
    if (textSearch.length > 0) {
      $scope.List2 = $scope.List1.filter(function (item) {
        return Object.keys(item).some(function (key) {
          return angular.isString(item[key]) && item[key].toLowerCase().search(textSearch) !== -1
        });
      });
    }
    else {
      $scope.List2 = [];
    }
  }
});

1 个答案:

答案 0 :(得分:0)

您第一次是对的:您应该通过使用ng-click调用函数来处理此逻辑

您的按钮可能看起来像这样:

<button ng-click="addStation(test)>{{test.name}}</button>"

在您的控制器中,您的功能可能如下所示:

function addStation(station) {
  $scope.txtSearch = station
  $scope.List2 = [] 
}