【问题标题】:Autocomplete using only Angularjs仅使用 Angularjs 自动完成
【发布时间】:2015-02-26 10:33:57
【问题描述】:

这是使用 AngularJS 并且不使用任何 Jquery 资产实现自动完成功能的最佳方式。请帮我举一些例子。

【问题讨论】:

  • 使用 angular-ui-typeahead

标签: angularjs autocomplete


【解决方案1】:

查看

<div ng-app='MyModule'>
    <div ng-controller='DefaultCtrl'>
        <input auto-complete ui-items="names" ng-model="selected">
        selected = {{selected}}
    </div>
</div>

控制器

function DefaultCtrl($scope) {
    $scope.names = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean", "paul", "pierre", "nicolas", "alfred", "gerard", "louis", "albert", "edouard", "benoit", "guillaume", "nicolas", "joseph"];
}

指令

angular.module('MyModule', []).directive('autoComplete', function($timeout) {
    return function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: scope[iAttrs.uiItems],
                select: function() {
                    $timeout(function() {
                      iElement.trigger('input');
                    }, 0);
                }
            });
    };
});

DEMO

【讨论】:

    【解决方案2】:

    查看

    <div class>
        <h2>AngularJS Autocomplete</h2>
        <input type="text" class="form-control" placeholder="Search for city" name="city" ng-model="city" ng-keyup="complete(city)">
        <ul class="list-group" >
          <li class="list-group-item" ng-repeat="cityname in filteredCity" ng-click="fillTextbox(cityname)">
            {{cityname}}
          </li>
        </ul>
      </div>
    

    将此添加到您的 CONTROLLER 中:

    $scope.cityList = ["Chennai", "Bangalore", "Hyderabad", "Coimbatore", "Mumbai", "Allahabad", "Delhi", "Kadapa", "Anantapur", "Tirupati", "Chandigarh", "Kolkata", "Srinagar"]
    $scope.complete = function(string) {
      if(string.length !== 0) {
        var output = [];
        angular.forEach($scope.cityList, function(city) {
          if(city.toLowerCase().indexOf(string.toLowerCase()) >= 0) {
            output.push(city);
          }
        });
        $scope.filteredCity = output;
      }
      else {
        $scope.filteredCity = null;
      }
    };
    
    $scope.fillTextbox = function(string) {
      $scope.city = string;
      $scope.filteredCity = null;
    };
    

    非常适合我,希望也适合你...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-04
      • 2013-09-21
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 2017-09-10
      相关资源
      最近更新 更多