在AngularJS指令模板中的元素上测试focus()

时间:2014-01-28 16:17:13

标签: javascript jquery angularjs jasmine jasmine-jquery

给出以下指令

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');
            };
        }
    };
});

我已经测试过焦点观察器在浏览器中工作,但我希望能够在单元测试中触发它。这是我尝试过的,但它没有用。

var element = angular.element('<div my-directive></div>');
$compile(element)($scope);
$scope.$digest();
element.find('input')[0].focus();

我可以看到我正确地使用find调用进入输入框,我希望代码能够在输入框中触发焦点事件,但是没有任何事情发生。我在这里缺少什么?

1 个答案:

答案 0 :(得分:17)

当尝试触发角度元素上的事件时,应该使用triggerHandler()函数,它只是jqLit​​e函数而不是角度函数,然后将事件作为字符串参数传递,如下所示。

element.find('input').triggerHandler('focus');

要对角度元素执行任何其他功能,请阅读文档here,它会显示角元素可用的函数列表