Search code examples
angularjsangularjs-directiveangularjs-scope

Injecting data objects into a directive factory in AngularJS


So I have a directive that takes in data objects as an argument into the scope. The problem is that I handle all my data in my service layer.

So this is some normal non-directive code:

angular.module('app').factory('appFactory', ['appValues', function(appValues) {
    var getStuff = function() { return appValues.stuff; };
}]);

But if want to reuse the factory inside a directive and get appValues as an argument:

angular.module('app').directive('myDir', [function() {
    return {
    ...
        scope: {
            values: '='
        }
    ....
    };
}]);

But this puts it on the scope and not into my data layer. So now I need to send the values object to every function call in my directive factory:

angular.module('app').factory('myDirFactory', [function() {
    var getStuff = function(values) { return values.stuff; };
}]);

Is there any good pattern to solve this and keep data in the data-layer and bypass the scope/controller?

Also, the factory will be a singleton shared amongst instances of the directive? How should I solve that then? Create a new injector somehow? Submit to putting lots of data object logic into the controller (which I've been thought not to do)?


Solution

  • It was a while ago, and I guess that a simple soultion is simply to provide an function initialize(value) {... return {...};} and then the returned object has access to the value argument without providing it as a parameter everywhere:

    angular.module('myDir').factory('myDirFactory', [function() {
    
      var initialize = function(values) {
        var getStuff = function() {
          return values;
        };
    
        return {
          getStuff: getstuff;
        };
      };
    
      return {
        initialize: initialize
      };
    }]);