4

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) 

2 Answers 2

9

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)
Sign up to request clarification or add additional context in comments.

Comments

-1

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
};

1 Comment

This is service locator anti-pattern.

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.