Pregunta

I'm having some headaches with scope, not Angular scope but JavaScript itself.

I have a factory called chartParsingHelpers it's something like this:

angular.module('myApp')
  .factory('chartParsingHelpers',['dateUtils', function(dateUtils){
    return {
      getInitArray : function(){
        return [ 'Stuff', 'Stuff 2' ];
      },
      doFancyStuff : function (data){
        var initArray = this.getInitArray();
      }
    };
  }]);

That works great if I inject chartParsingHelpers anywhere and call doFancyStuff it will work. However, I wanted to have some config for my fancy charts since they share code structure and I think is great to share that config around directives and all friends so, I created something like this:

angular.module('visits')
  .factory('ChartTypes',['dateUtils', 'chartParsingHelpers', function(dateUtils, chartParsingHelpers){
    return {
      config : [
        {
          name : 'Chart 1',          
          xAxisFormatter : dateUtils.getFullHour,
          parseMethod : chartParsingHelpers.doFancyStuff
        }
      ]
    };
  }]);

My plan is to inject ChartTypes into a Controller and into a directive (for now) but then I receive this error:

TypeError: Object #<Object> has no method 'getInitArray'

If I look into the value of this then... well, it's the value of the object itself with name, xAxisFormatter and so on...

How could I approach this? Is this the right way?

¿Fue útil?

Solución

The context of this in chartParsingHelpers.doFancyStuff is probably the issue. I would create the factory like this:

angular.module('myApp')
  .factory('chartParsingHelpers',['dateUtils', function(dateUtils){

    var self = {};

    self.getInitArray = function() {
      return ['Stuff', 'Stuff 2'];
    };

    self.doFancyStuff = function(data) {
      var initArray = self.getInitArray();
    };

    return self;
 }]);

That way you make sure that you're always referencing that object.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top