我有一堆指令,他们有相同的逻辑:
angular.module('playrApp').directive('oneofmydirective', [
function() {
'use strict';
return {
restrict: 'E',
replace: true,
scope: {
listeners: '@'
},
link: function($scope, $element) {
$scope.listeners = [].concat(($scope.listeners||'').split(' '));
_.forEach($scope.listeners, function(listener){
$scope.$on(listener, $scope['on'+listener]);
});
},
unlink: function($scope, $element) {
_.forEach($scope.listeners, function(listener){
$scope.$off(listener, $scope['on'+listener]);
});
},
controller: ['$scope', '$element',
function($scope, $element) {
$scope.onMyCustomEvent1 = function() {
// handle event
};
$scope.onMyCustomEvent2 = function() {
// handle event
};
}]
}
]);
所以我可以根据需要使用它们激活听众:
<!-- Sometimes -->
<oneofmydirective></oneofmydirective>
<!-- And sometimes -->
<oneofmydirective listeners="MyCustomEvent1 MyCustomEvent2"></oneofmydirective>
如何重构我的代码以在每个指令中共享它?