I have a function that clears an input on blur. It's designed for use with Angular Materials, and I've created a directive for when this functionality is needed.
function clearTextOnBlurLink(scope, element, attrs, controller) {
$timeout(function() {
var input = element.find('input');
input.on('blur', function(e){
setTimeout(function(){
input.val('');
input.triggerHandler('input');
}, 100);
});
},0);
}
I'm trying to test it out, but having some trouble getting it to work.
Here's my testing code:
beforeEach(inject(function(_$rootScope_, _$compile_, _$timeout_) {
$scope = _$rootScope_.$new();
$compile = _$compile_;
$timeout = _$timeout_;
$scope.searchText = 'blah';
element = angular.element('\
<div mx-clear-on-blur>\
<input ng-model="searchText1">\
</div>\
');
element = $compile(element)($scope);
$scope.$apply();
$timeout.flush();
}));
it('clears text on blur', function() {
var input = element.find('input').eq(0);
expect(input.val()).toBe('blah');
expect($scope.searchText).toBe('blah');
input1.triggerHandler('blur');
expect(input.val()).toBe('');
expect($scope.searchText).toBe('');
});
After making some changes by replacing setTimeout with $timeout, I managed to make it work. Is there a smoother way to achieve this without using two timeouts?