Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

fix(ngEventDirs): check for $rootScope.$$phase in event handler and d… #14674

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/ng/directive/ngEventDirs.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,12 @@ forEach(
var callback = function() {
fn(scope, {$event:event});
};
if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
if (!$rootScope.$$phase) {
scope.$apply(callback);
} else if (forceAsyncEvents[eventName]) {
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
callback();
}
});
};
Expand Down
42 changes: 42 additions & 0 deletions test/ng/directive/ngEventDirsSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,46 @@ describe('event directives', function() {
}));

});

describe('click', function() {

it('should call the listener synchronously if inside of $apply',
inject(function($rootScope, $compile) {
var watchedVal;

element = $compile('<button type="button" ng-click="click()">Button</button>')($rootScope);
$rootScope.$watch('value', function(newValue) {
watchedVal = newValue;
});
$rootScope.click = jasmine.createSpy('click').and.callFake(function() {
$rootScope.value = 'newValue';
});

$rootScope.$apply(function() {
element.triggerHandler('click');
});

expect($rootScope.click).toHaveBeenCalledOnce();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't actually check that it is called synchronously (e.g. it might be called outside of the $apply() block).
You could use the same approach as below (using a $watch).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated the PR to use the same checks for both tests

expect(watchedVal).toEqual('newValue');
}));

it('should call the listener synchronously if outside of $apply',
inject(function($rootScope, $compile) {
var watchedVal;

element = $compile('<button type="button" ng-click="click()">Button</button>')($rootScope);
$rootScope.$watch('value', function(newValue) {
watchedVal = newValue;
});
$rootScope.click = jasmine.createSpy('click').and.callFake(function() {
$rootScope.value = 'newValue';
});

element.triggerHandler('click');

expect($rootScope.click).toHaveBeenCalledOnce();
expect(watchedVal).toEqual('newValue');
}));

});
});