0

My question is best explained with a layout of my template.

<body>

   <my-directive option1="myVar"></my-directive>

   <ui-view></ui-view>

</body>

As you can see I have a ui-view that will switch views/controllers with different state. The issue is that only one of those states contains the necessary and logical configuration variables within its scope for 'my-directive'. How can I pass those variables to the directive? I am trying to avoid using $rootScope for this, but it currently seems to me like the best choice.

naughty boy
  • 2,089
  • 3
  • 18
  • 28
  • You mean the directive should be shown only when on specific state or does it change according to each state? – Daniel Mar 27 '16 at 15:02
  • To be more specific, the directive is a header which has a log-in/log-out button among other things. The ui-view has two states : one provides users with a display of an item while another state will enable the user to edit the item. I would only like the log-in button to be visible only when the view is in the view state. The header still needs to display regardless of the state though which is why I didn't nest it. – naughty boy Mar 27 '16 at 15:13
  • You can do it inside the `directive` template, `ng-if="$state.current.name === state1"` etc... – Daniel Mar 27 '16 at 15:21

1 Answers1

0

There is several solutions, it depends on your configuration variables:

If your configuration variables are initialized at bootstrap and never changes, you could use "constants".

See: https://docs.angularjs.org/api/auto/service/$provide#constant

If your configuration variables may change, you could use "values"

See: https://docs.angularjs.org/api/auto/service/$provide#value

The last way i know is to use a services

See: https://docs.angularjs.org/api/auto/service/$provide#service

This post explains the differences between those 3 functionalities: https://gist.github.com/demisx/9605099

Edit: "How to pass thoses solutions in a view directly"

One possible solution would be to initialize the $rootScope on run function like this:

angular.module('myApp')
  .run(function ($rootScope, yourConfigurationVariables) {
      $rootScope.aSpecificNameWichReferenceYourChoice = yourConfigurationVariables;
   });

See this post: Can I directly access module constant from HTML under AngularJS

Community
  • 1
  • 1
Aliz
  • 736
  • 1
  • 11
  • 25
  • Great, this seems to be the way, but the article doesn't mention how to reference those values from your template.. do you happen to know? – naughty boy Mar 27 '16 at 15:17
  • Did you define a controller in your directive ? – Aliz Mar 27 '16 at 15:22
  • they are declared module wide? isn't there a module wide object I can reference like $root? declaring a controller on the directive to only to get those values seems kinda off to me. – naughty boy Mar 27 '16 at 15:31