1

I have this code bellow and is working well, I would like to know how can make this variable show in my root-scope?

the problem is I am using now different controllers and directives so:

if I put this in directive1:

<a href="" ng-click="showme=true">Show</a>
<button ng-click="showme=false">Hide</button> 

and this in directive2 does not work:

 <div class="wrapper">
        <p ng-hide="showme">It will appear here!</p>
        <h2 ng-show="showme">This is mah content, yo!</h2>
      </div>

full code working if in the same directive html + angular

 <div ng-app="">
      <h1>Ng-show & ng-hide</h1>
      <p class="description">Click on the "show"-link to see the content.</p>
      <a href="" ng-click="showme=true">Show</a>
      <button ng-click="showme=false">Hide</button> 

      <div class="wrapper">
        <p ng-hide="showme">It will appear here!</p>
        <h2 ng-show="showme">This is mah content, yo!</h2>
      </div>

    </div> 

I heard about I can use something like: $rootScope but how I can implement this in that case? thank you.

raduken
  • 2,091
  • 16
  • 67
  • 105

1 Answers1

2

You need to make sure show is set on the $rootScope. Convenient place for this is run block:

.run(['$rootScope', function($rootScope) {
  $rootScope.show = false
}])

After that all scopes will inherit show from its parent.

Another option. You can actually directly refer to $rootScope from any of your template, this is probably simplest solution:

<a href="" ng-click="$root.show = true">Show</a>
<button ng-click="$root.show = false">Hide</button>
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • thanks my jshint complain about it: 20 |.run(['$rootScope', function($rootScope) { ^ Expected an identifier and instead saw '.'. 20 |.run(['$rootScope', function($rootScope) { ^ Expected an assignment or function call and instead saw an expression. 20 |.run(['$rootScope', function($rootScope) { ^ Missing semicolon. 20 |.run(['$rootScope', function($rootScope) { ^ 'run' is not defined. – raduken Jul 14 '16 at 10:05
  • 1
    Because it's not valid syntax. `.run` is a method of the angular module. – dfsq Jul 14 '16 at 10:06