由于以下指令
directive('myDirective', function() {
return {
restrict: 'A',
scope: {},
replace: false,
template: '<input ng-focus="onFocus()" type="text" />',
link: function(scope, element, attr) {
scope.onFocus = function() {
console.log('got focus');
};
}
};
});
我测试过,重点守望者在浏览器中工作,但我希望能够触发它在单元测试。这是我做过尝试,但它不工作。
I've tested that the focus watcher works in a browser, but I'd like to be able to trigger it in a unit test. This is what I've tried but it isn't working.
var element = angular.element('<div my-directive></div>');
$compile(element)($scope);
$scope.$digest();
element.find('input')[0].focus();
我可以看到,我得到正确与查找调用的输入框,我会期望code触发输入框的焦点事件,但什么也没有发生。缺少什么我在这里?
I can see that I am correctly getting to the input box with the find call, and I would expect that code to trigger the focus event on the input box, but nothing is happening. What am I missing here?
推荐答案
在试图触发角元素的事件,应该使用 triggerHandler ()函数这是真的很jqLite功能,而不是angulars再通事件作为字符串参数,如下图所示。
When trying to trigger events on angular elements, one should use the triggerHandler() function which is just really jqLite function and not angulars and then pass in the event as a string parameter as shown below.
element.find('input').triggerHandler('focus');
要角元素上执行其他功能,在这里阅读文档 ,它表明你的列表可用角元素的功能
To perform any other functions on an angular element, read the documentation here, it shows you a list of functions available to angular elements
相关推荐
最新文章