0

New to Angular and I am trying to figure out Value. I am trying to save a value that I can later inject into my controller but for some reason, it breaks. If you run the plnkr sample, it will work, code gets to the controller. If you comment out line 68 and un-comment 67, it breaks the application. Line 41, I just set a value which is what I want to pass into my controller.

Why would this not work?

http://plnkr.co/edit/SnOm2r?p=options

TheHippo
  • 61,720
  • 15
  • 75
  • 100
user147372
  • 39
  • 8

2 Answers2

1

There is no AppConfig...if you want to inject AppConfig it has to exist somewhere, a directive, a service, a factory, SOMETHING. You don't currently have one being loaded.

Snowburnt
  • 6,523
  • 7
  • 30
  • 43
  • isn't it defined on line 41? How do I pass the contents of AppConfig to my controller? – user147372 Feb 13 '14 at 14:18
  • If I put line 41 outside of the main.config it works as expected. see also this question: http://stackoverflow.com/questions/15937267/inject-service-in-app-config – Snowburnt Feb 13 '14 at 14:35
0

Your issue is a timing issue. The controller is created before the value is set so it doesn't have access.

If you create like this:

var mainApp = angular.module("Test", ["ui.router"]);
mainApp.value("AppConfig", 1.0); 

Then you can access it right away. If you have to set it asynchronously (i.e. you plan to set it as the result of a call) then the best way is probably to inject the $injector instead of the AppConfig. Then you can do:

if ($injector.has("AppConfig")) { value = $injector.get("AppConfig"); }

Even better may be to move that into a service with a promise that can return the value once it's fetched then cache it for subsequent calls.

Jeremy Likness
  • 7,531
  • 1
  • 23
  • 25
  • Thanks but since I am little new, could you possible change the plnkr to reflect that change? Also I rather place that in a service (yes that was test, I need to get some json back) but I need to get my json before the routes are set and I read that this is the only way. – user147372 Feb 13 '14 at 18:25
  • Sure. This works for configuring it "up front" http://plnkr.co/edit/SdFNnuVSSjS0zwXFWyTp?p=preview for a promise you would use the $q service – Jeremy Likness Feb 13 '14 at 19:18