我尝试使用 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 />
指令仍然没有调用 AutoCompleteService。我在这里做错了什么吗?
最佳答案
这并不是说您的服务没有被指令调用,而是您的指令根本没有根据您提供的 html 被调用。您应该通过将驼峰式表示法转换为虚线表示法来调用指令,如下所示:
<input id="search" ng-model="searchText" auto-complete />
您可以在AngularJS Directive Documentation中找到有关指令匹配的所有信息。 .
关于javascript - AngularJS 中自动完成指令的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27656130/