这是包装jquery-ui自动完成
的指令angular.module('myApp.directives', [])
.directive('autocomplete', function () {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<input ng-model="autocomplete" type="text"/>',
link: function (scope, element, attrs) {
scope.$watch(attrs.typedvalue, function () {
element.autocomplete({
search: function (event) {
scope[attrs.typedvalue] = this.value;
scope[attrs.fullselection] = '';
scope[attrs.selectionid] = '';
scope[attrs.shortselection] = '';
scope.$apply();
},
source: scope.fetchList,
select: function (event, ui) {
scope[attrs.fullselection] = ui.item.label;
scope[attrs.selectionid] = ui.item.itemId;
scope[attrs.shortselection] = ui.item.value;
scope.$apply();
}
});
});
}
};
});
我正在尝试使用以下测试对其进行单元测试(遵循此处的说明https://github.com/vojtajina/ng-directive-testing):
describe('Directives', function () {
beforeEach(module('myApp.directives'));
describe('autocomplete directive', function () {
var elm, scope;
beforeEach(inject(function ($rootScope, $compile) {
elm = angular.element('<autocomplete fullselection="fullDstn" shortselection="dstn" selectionid="geonameId" typedvalue="typedValue" id="DstnSlctr"/>');
scope = $rootScope;
$compile(elm)(scope);
scope.$digest();
}));
it('should create input', inject(function ($compile, $rootScope) {
expect(elm.id).toBe('DstnSlctr');
expect(elm.prop('tagName')).toBe('INPUT');
debugger;
}));
});
});
但是我收到了一个错误:
TypeError: Object [[object HTMLInputElement]] has no method 'autocomplete'
at Object.fn (C:/Users/kmukhort/Documents/_files/TMate/AngularTest/a
pp/js/directives.js:13:33)
元素行上的元素自动完成({ 我怀疑在$ compile时,jquery-ui功能没有附加到元素上。 我在testacular.config中引用jquery-ui库
basePath = '../';
files = [
...
'app/lib/jquery-ui-*.js',
];
请你告诉我,我做错了什么?
谢谢! 塞梅
答案 0 :(得分:1)
我认为你需要替换:
element.autocomplete(...);
使用:
$(element).autocomplete(...);