如何在angularjs自动完成中修复此错误" iElement.autocomplete不是一个函数"

时间:2016-05-03 08:50:14

标签: angularjs autocomplete

我必须为国家/地区下拉实现自动完成。我正在使用angularjs 1.4版本。

我引用此网站click here来实现此自动完成功能。

但显示此错误" iElement.autocomplete不是一个函数"在实现上面的代码时。我需要包含任何js文件

这是我的HTML代码

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

js file

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

    app.controller('DefaultCtrl', function($scope) 
    {
     $scope.countries = [ 
        {name: 'Afghanistan', code: 'AF'},
        {name: 'Antigua and Barbuda', code: 'AG'},
        {name: 'Bahamas', code: 'BS'},
        {name: 'Cambodia', code: 'KH'},
        {name: 'Cape Verde', code: 'CV'}];
    });


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

提前谢谢

1 个答案:

答案 0 :(得分:3)

您所指的示例似乎是旧的(角度1.0.0),我不确定这是否应该使用当前的1.5。无论如何,我建议你看一下Typeahead指令from Angular-UI。还有一个例子,你可以编辑以满足你的需要。

以下是使用您的数据的working example

HTML:

<div ng-controller="MainCtrl">
    <h4>Custom templates for results</h4>
    <pre>Model: {{selected | json}}</pre>
    <input type="text" ng-model="selected" uib-typeahead="country as country.name for country in countries | filter:{name:$viewValue}" class="form-control" typeahead-show-hint="true" typeahead-min-length="0">
</div>

JS:

angular
  .module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap'])
  .controller('MainCtrl', function($scope, $http) {
    //ngModel value
    $scope.selected = undefined;
    //lookup values
    $scope.countries = [ 
      {name: 'Afghanistan', code: 'AF'},
      {name: 'Antigua and Barbuda', code: 'AG'},
      {name: 'Bahamas', code: 'BS'},
      {name: 'Cambodia', code: 'KH'},
      {name: 'Cape Verde', code: 'CV'}
    ];
  });