如何在不使用Jquery的情况下使用angularJs创建自动完成功能?

时间:2016-11-18 08:13:07

标签: angularjs

我正在表单中创建一个标记字段,我想让这个字段自动完成,以便它显示来自我的$ scope变量的建议,即本地源。

<tags-input ng-model="tModel.tags"></tags-input>

但是,由于我的项目does not use jquery I cannot use the jquery autocomplete feature。有任何方法可以使用angularJs进行自动填充。

PS:我在stackoverflow中搜索了很多答案,但没有一个对我有效。

2 个答案:

答案 0 :(得分:0)

尝试使用Angular UI Bootstrap Typeahead指令。

答案 1 :(得分:0)

这是关于如何实现ui-bootstrap typeahead的基本DEMO。我已经使用异步调用来获取函数cities($viewValue)的提前类型结果,而不是在这里传递一个列表对象。

您的HTML将使用以下脚本

<html>

  <head>
     <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
  <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.1.4.js"></script>
    <script src="example.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  </head>

  <body ng-app="plunker">
    <div class="container-fluid" ng-controller="TypeaheadCtrl">
      <pre>Model: {{result | json}}</pre>
      <input type="text" ng-model="result" class="form-control" uib-typeahead="address for address in cities($viewValue)" />

    </div>
  </body>

</html>

你的JS控制器将有以下代码。

var app = angular.module('plunker', ['ui.bootstrap']);

app.factory('dataProviderService', ['$http', function($http) {
    var factory = {};
    factory.getCities = function(input) {

      return  $http.get('//maps.googleapis.com/maps/api/geocode/json', {
            params: {
                address: input,
                sensor: false
            }
        });

    };

    return factory;
}]);

app.controller('TypeaheadCtrl', ['$scope', '$log','$http', 'dataProviderService', function($scope, $log,$http, dataProviderService) {
    $scope.cities = function(viewValue) {

     return   dataProviderService.getCities(viewValue).then(function(response) {
            return response.data.results.map(function(item) {
                return item.formatted_address;
            });
        });

    };


}]);