Gaspe
Gaspe

Reputation: 11

Inject one value into another in AngularJS?

I have a value that looks like this:

app.value('opportunityStages', [
  'NEGOTIATION',
  'PROPOSAL',
  'PERCEPTION_ANALYSIS'
]);

That works. I want to inject that value into another value, so I tried this:

app.value('opportunities', [
  'opportunityStages', // Failed attempt to inject opportunityStages

  [
    { account: 'Caterpillar',
      stage: opportunityStages[0], // Failed attempt to use the values
      closeDate: new Date(2014, 7, 13)
    }
    // More opportunity objects that follow are omitted
  ]);

I really did not expect this to work because my understanding is that you can only inject things into functions.

I could hardcode opportunityStages inside opportunities, like this:

app.value('opportunities', [
  { account: 'Caterpillar',
    stage: 'NEGOTIATION',
    ...
  },
  ...
]);

However, hardcoding the values is error prone and not DRY, so I'd rather avoid it. How does one handle this the Angular Way?

Upvotes: 1

Views: 30

Answers (1)

Sunil D.
Sunil D.

Reputation: 18193

Use a factory instead of a value:

app.factory('Opportunities', ['opportunityStages', function(opportunityStages) {

  var myFactory = {
    stage: opportunityStages[0]
  };

  return myFactory;
}]);

Upvotes: 1

Related Questions