Shared Directive Functionality


#1

Hi there,

Current Scenario

I’ve got a dozen or so directives that are all fundamentally similar, but different in key places. Right now, whenever I make what I am calling a “core” change, I have to change the source code of each directive individually.

An example of some repeated code is…

/**
* Provide a colour selecting helper function.
* this function only gets used if the colour-array attribute
* is set
**/
scope.color = function() {
	return function(d, i) {
		return scope.colorArray[i];
	}
}

Aim

I would like these directives to share a set of core functions, so I am not repeating code a dozen times.

My Idea

Where possible, pass the scope, and the dependencies to another function and work with things there. e.g.:

// A global shared function
function refreshData(scope,element,attrs,$http,$location){
  // Super stuff here
}

// Within the link function of a directive
if(scope.something == true){
  refreshData(scope,element,attrs,$http,$locaiton)
}

Is that considered bad practice, or is that OK?

My Issue

For my first example, I used scope.color = function()… and I’m not entirely sure how I can actually share a “core” function to multiple directives when it’s the actual function being passed elsewhere. Sorry, I’m not sure I explained that well but hopefully someone understands.

So, can anyone provide any input with this?

Cheers
-Chris


#2

You could put your core functions into a service and reference to this service from every directive.