Raduken Raduken - 4 months ago 56
AngularJS Question

Ng-show & ng-hide using $rootScope in my project?

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.

Answer

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>