Testing focus() on an element in an AngularJS directive template

戏子无情 提交于 2020-01-24 03:50:46

问题


Given the following directive

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();

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?


回答1:


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



来源:https://stackoverflow.com/questions/21411003/testing-focus-on-an-element-in-an-angularjs-directive-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!