测试重点()的元素在AngularJS指令模板 [英] Testing focus() on an element in an AngularJS directive template

查看:118
本文介绍了测试重点()的元素在AngularJS指令模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下指令

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 ()函数这是真的很jqLit​​e功能,而不是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

这篇关于测试重点()的元素在AngularJS指令模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆