3

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 For the OP it might be worth checking the difference between factories and services... a summary: a factory returns an object given by factory function (e.g. self) while a service returns a new instance of the function (e.g. new function(dateUtils))
It could be imo a good idea use like myApp.constant('mySettings', { config:['Stuff', 'Stuff 2'] });
Thanks @elclanrs worked great didn't thought about doing that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.