Last active
January 3, 2018 09:33
-
-
Save rewoo/a85e1b43eca7b457fc8c to your computer and use it in GitHub Desktop.
Automatic unbind pattern for event bindings in directives using AngularJS
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
angular.module('app', []) | |
.directive('myAwsomeDirective', function($rootScope) { | |
return { | |
restrict: 'A', | |
link: function(scope) { | |
// $scope.$on() returns an unbind function of the binding | |
// | |
// So use the bind function directly within scope's $destroy event | |
// to unbind event automatically. | |
scope.$on('$destroy', $rootScope.$on('my:event', function() { | |
// your event code here | |
})); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment