Page 436 - AngularJS权威教程
P. 436
416 第 31 章 构建 Angular Chrome 应用
ngModel: '='
},
compile: function(tEle, tAttrs) {
//编译函数
return function(scope, ele, attrs, ctrl) {
//链接函数
}
}
}
});
因为这里会创建一个新元素,因此需要使用compile函数而不只是link函数和模板,因为
<ul>元素不能嵌套在一个<input>元素中。
这里不会深入介绍compile函数的工作原理,只会创建一个新元素,然后为它设置绑定:
// ...
compile: function(tEle, tAttrs) {
var tplEl = angular.element('<div class="typeahead">' +
'<input type="text" autocomplete="off" />' +
'<ul id="autolist" ng-show="reslist">' +
'<li ng-repeat="res in reslist" ' +
'>{{res.name}}</li>' +
'</ul>' +
'</div>');
var input = tplEl.find('input');
input.attr('type', tAttrs.type);
input.attr('ng-model', tAttrs.ngModel);
tEle.replaceWith(tplEl);
return function(scope, ele, attrs, ctrl) {
// ...
在链接函数内,我们需要给keyup事件绑定一个函数,同时还要检查在输入字段中至少有最少
数量的字符。只要发现有最少数量的字符,就运行通过使用指令设置的函数,来提取自动建议值。
Autocomplete API
让我们来看看如何调用这个指令:通过传递一个函数调用给auto-fill指令,然后将位置值
绑定给user.location。
<input type="text"
ng-model="user.location"
auto-fill="fetchCities"
autocomplete="off"
placeholder="Location" />
在Weather服务中,我们会创建另一个函数明确地调用autocomplete API,并解析一个带有
与查询词汇对应的完整建议列表的promise。
getWeatherForecast: function(city) {
// ...
},
getCityDetails: function(query) {
var d = $q.defer();
$http({