1fabiopereira 1fabiopereira - 5 months ago 33
AngularJS Question

Provider Recipe

I have a directive that has a provider, given that this provider can be configured several times in the same application and each instance of the directive take the values of a different configuration, but all instances of the directive always assume the same configuration. I wonder how I can fix this ?

.provider('tabNavBarConfig', function tabNavBarConfigProvider() {

this.setNamesTab = function (array) {
this.tabs = array || new Array("tab1", "tab2", "tab3", "tab4");
}


this.setTabActivated = function (nun) {
this.tabActivated = nun;
}


this.setTabActivatedColor = function (color) {
this.tabActivatedColor = color || "#f00";
}


this.setBackgroundColor = function (color) {
this.backgroundColor = color || "#ddd";
}


this.setBackgroundBlockColor = function (color) {
this.backgroundBlockColor = color || "#fff";
}


this.setTextColor = function (color) {
this.textColor = color || "#000";
}


/* return instance of provider*/
this.$get = function () {
return this;
};

})

Answer

It's important to note that AngularJS services are always singletons. This means that, once AngularJS constructs a service object, the same instance is reused throughout your app. Therefore, configuring the provider several times will change the values in the single instance generated by the service factory. Thus, all your directives will get the same values and not private ones. Could you please give us more details about your case ?

Update 1:

After taking a look at the file, the correct way to achieve your aim is to use the directive controller. The link function will receive the controller instance as an argument:

function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }

This way you can access the configuration values specific to the directive instance. Also, the controller instance is shared among all directives, which allows the directives to use the controller as a communication channel.

I hope this is what you are looking for. Good luck.