AngularJS中的自动完成指令出现问题

Issue with Autocomplete Directive in AngularJS

本文关键字:指令 问题 AngularJS      更新时间:2023-09-26

我试图用 Angular 的"autocomplete"指令实现文本框自动完成,但它不被应用程序识别。这是我的应用程序:

var app = angular.module('app', [
'ngRoute',
'ngCookies',

]);

app.service('AutoCompleteService', ['$http', function ($http) {
return {
    search: function (term) {
        return $http.get('https://myapi.net/suggest?query='+term+'&subscription-key=XYZ').then(function (response) {
            return response.data;
        });
    }
};

}]);

app.directive('autoComplete', ['AutoCompleteService', function (AutoCompleteService) {
return {
    restrict: 'A',
    link: function (scope, elem, attr, ctrl) {
        elem.autocomplete({
            source: function (searchTerm, response) {
                AutoCompleteService.search(searchTerm.term).then(function (autocompleteResults) {
                    response($.map(autocompleteResults, function (autocompleteResult) {
                        return {
                            label: autocompleteResult.ID,
                            value: autocompleteResult.Val
                        }
                    }))
                });
            },
            minLength: 3,
            select: function (event, selectedItem) {
                // Do something with the selected item, e.g. 
                scope.yourObject = selectedItem.item.value;
                scope.$apply();
                event.preventDefault();
            }
        });
    }
};

}]);

我放置了指令名称如下:

<input type="text" id="search" ng-model="searchText" placeholder="Enter Search Text" autocomplete />

仍然不由指令调用自动完成服务。我在这里做错了什么吗?

并不是说你的服务不是从指令调用的,而是你的指令根本没有根据你提供的html调用。您应该通过将驼峰大小写表示法转换为虚线表示法来调用指令,如下所示:

<input id="search" ng-model="searchText" auto-complete />

您可以在 AngularJS 指令文档中找到有关指令匹配的所有信息。