Skip to content

Instantly share code, notes, and snippets.

@bcabanes
Last active August 29, 2015 14:23
Show Gist options
  • Save bcabanes/677305a013660ae7d55e to your computer and use it in GitHub Desktop.
Save bcabanes/677305a013660ae7d55e to your computer and use it in GitHub Desktop.
Angular directive conditional click: eactClickIf
(function(angular) {
'use strict';
angular
.module('app')
.directive('eatClickIf', directive);
directive.$inject = [
'$parse',
'$rootScope'
];
function directive($parse, $rootScope) {
// This ensure eatClickIf be compiled before ngClick.
return {
'priority': 100,
'restrict': 'A',
'compile': compile
};
function compile($element, attributes) {
var fn = $parse(attributes.eatClickIf);
return {
pre: function link(scope, element) {
var eventName = 'click';
element.on(eventName, function(event) {
var callback = function() {
if (fn(scope, {$event: event})) {
// Prevents ng-click to be executed.
event.stopImmediatePropagation();
// Prevents href.
event.preventDefault();
return false;
}
};
if ($rootScope.$$phase) {
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
});
},
post: function() {}
};
}
}
})(angular);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment