【问题标题】:Testing focus() on an element in an AngularJS directive template在 AngularJS 指令模板中的元素上测试 focus()
【发布时间】:2014-01-28 16:17:12
【问题描述】:

给定以下指令

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 调用正确地进入了输入框,并且我希望该代码能够触发输入框上的焦点事件,但没有发生任何事情。我在这里错过了什么?

【问题讨论】:

  • 我认为你不需要做element.find('input')元素输入标签
  • 替换设置为假。 element 是 div,其中包含的是输入标签。
  • 哦,我错过了那部分
  • 试试element.find('input').triggerHandler('focus');
  • $(element.find('input')[0]).triggerHandler('focus'); 没有这样的运气

标签: javascript jquery angularjs jasmine jasmine-jquery


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2016-12-07
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多