Last active
August 29, 2015 14:23
-
-
Save bcabanes/677305a013660ae7d55e to your computer and use it in GitHub Desktop.
Angular directive conditional click: eactClickIf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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