【发布时间】:2014-05-02 15:04:14
【问题描述】:
我有以下用于自动完成功能的 HTML 文本框。
<body ng-controller="HomeController" ng-init="init()">
<div class="col-xs-4 search-bar-position" >
<form role="search" >
<div class="input-group" >
<input auto-complete type="text" id ="search" value="abcd" class="form-control text-center" placeholder="Search Products" name="srch-term" id="srch-term" style="width:400px;height:30px;" ng-change="autoComplete()" ng-model="searchChar" />
<div class="input-group-btn">
<button class="btn btn-default" style="height:30px;" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
</body>
AngularJS 控制器如下。
angular.module('gbuyRef').controller('HomeController',function ($scope,$window,$http,$cookies) {
$scope.autoComplete = function() {
searchChar = $scope.searchChar
$http({
method : 'POST',
url : '/autoComplete',
data : {"searchChar" : searchChar},
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
// set the headers so angular passing info as form data (not request payload)
}).success(function(data, status, headers, config) {
$scope.products = JSON.parse(JSON.stringify(data));
$scope.product_list = $scope.products.products;
console.log($scope.product_list);
}).error(function(data, status, headers, config) {
$scope.status = status;
$window.alert("error")
});
}
});
AngularJS 指令如下:
angular.module('gbuyRef').directive('autoComplete', function() {
return {
restrict: 'A',
link: function(scope, elem, attr, ctrl) {
// elem is a jquery lite object if jquery is not present,
// but with jquery and jquery ui, it will be a full jquery object.
elem.autocomplete({
source: scope.product_list
});
}
};
});
当我尝试通过输入文本框来使用自动完成功能时,我在 firebug 中收到以下错误
TypeError: this.source is not a function this.source( { term: value }, this._response() );
$scope.product_list 正在从后端获取响应 [“samsung chromebook”、“sony playstation 4”、“sony vaio”、“sony vaio 17”] 当我在文本框中按 s 时
我确实看过其他帖子,但无法弄清楚实际的解决方案。 任何帮助将不胜感激。
【问题讨论】:
-
这个错误听起来好像您在调用 HTTP 请求之前没有将
product_list初始化为任何内容。另外,我认为您需要调用autocomplete来重新绑定建议列表,每次它被 HTTP 请求更新(即使用$watch)。 -
@miqid : 你能告诉我如何在 AngularJS 指令中使用 $watch。
-
当然。我刚刚取出了您提供的代码的相关部分来破解一个简单的示例来演示。 JSBin here.
-
@miqid :非常感谢,这行得通。 :)
标签: jquery angularjs autocomplete