仅使用Angularjs自动完成

时间:2014-12-30 09:06:49

标签: angularjs autocomplete

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

2 个答案:

答案 0 :(得分:0)

查看

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

<强> CONTROLLER

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"];
}

DIRECTIVE

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

答案 1 :(得分:0)

查看

<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;
};

对我来说很完美,希望也适合你......