JayPrime2012
JayPrime2012

Reputation: 2692

AngularJS Inject Fallback

I have a situation where sometimes I have locals passed into the controller and sometimes not.

What I'd like to be able to do is if the "locals" are not available, not throw exception and instead just call the Controller and leave locals == null.

.controller('SomeCtrl', ['$scope', 'locals', function ($scope, locals) {
  if (!locals) // do something
  else // do something else
};

In one case controllers are being created using the $controller service. $controller('SomeCtrl', { locals: 'some locals');

But in other cases I have no control over how the controller is instantiated and the locals are not available. I wish Angular would just pass undefined like normal javascript...

THIS ISN'T COOL:

Error: Unknown provider: localsProvider <- locals
    at Error (<anonymous>)
    at http://localhost:1573/Scripts/angular.js:2832:15
    at Object.getService [as get] (http://localhost:1573/Scripts/angular.js:2960:39)
    at http://localhost:1573/Scripts/angular.js:2837:45
    at getService (http://localhost:1573/Scripts/angular.js:2960:39)
    at invoke (http://localhost:1573/Scripts/angular.js:2978:13)
    at Object.instantiate (http://localhost:1573/Scripts/angular.js:3012:23)
    at $get (http://localhost:1573/Scripts/angular.js:4981:24)
    at http://localhost:1573/Scripts/angular.js:4560:17
    at forEach (http://localhost:1573/Scripts/angular.js:137:20) 

Upvotes: 4

Views: 508

Answers (2)

bekite
bekite

Reputation: 3444

you can use the $injector service to inject dependencies.

.controller('SomeCtrl', ['$scope', '$injector', function ($scope, $injector) {
  try {
    service = $injector.get('locals');
  } catch {}
  if (!service) // do something
  else // do something else
};

Upvotes: -1

JayPrime2012
JayPrime2012

Reputation: 2692

It turns out you can just set 'locals' to undefined and it will use the correct locals if they are available.

angular.module('module').value('locals', undefined)

Upvotes: 9

Related Questions