2

I want to store a variable within $rootScope. When I have a structure like this it all works OK, the second div displays the value:

<html ng-app>
  ...
  <body>
    <button ng-click="$rootScope.pr = !$rootScope.pr"></button>
    <div ng-class="{some:$rootScope.pr}">{{$rootScope.pr}}</div>
  </body>

But when I have a structure like this:

<body>
    <div class="root-scope-value-1">{{$rootScope.mobileMenuCollapsed}}</div>
    <div class="content-wrapper" ng-controller="MainController">
        <nav class="navbar navbar-custom navbar-fixed-top" role="navigation">
            <div class="container">
                <div class="navbar-header">
                    <div class="root-scope-value-2">{{$rootScope.mobileMenuCollapsed}}</div>
                    <button ng-click="$rootScope.mobileMenuCollapsed = !$rootScope.mobileMenuCollapsed">

The div with class root-scope-value-2 shows the value from $rootScope.mobileMenuCollapsed, but the div with class root-scope-value-1 which is up the DOM doesn't. Why so?

PSL
  • 123,204
  • 21
  • 253
  • 243
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

1

You do not have to use $rootScope in the view, scope's are implicitly bound to the views (even in case of controller As syntax, the alias becomes a property on the $scope which has the value of the controller instance reference). All the scopes ($scope.$new()) except isolated scope($scope.$new(true)) are inherited ultimately from rootscope so you will have the properties available on the rootScope automatically available on the scope. So here your controller MainController's scope is inherited from the rootScope.

Plnkr

As a better practice always place properties on an object on the rootscope (As in the plunker) just so when you make any changes to the properties (properties of an object on the rootScope) from the child scope, the changes gets reflected on the parent as well, because both of them point to the same reference.

PSL
  • 123,204
  • 21
  • 253
  • 243
  • So basically since `ng-controller` creates new scope this scope had `$rootScope` property created on it by angular, while for the `root-scope-value-1` the `rootScope` property was defined on `rootScope`, correct ? – Max Koretskyi Sep 12 '14 at 15:20
  • 1
    @Maximus Yes the scope created for your controller in this case is prototypically inherited from rootscope. if you have a controller wrapping this controller then this will be prototypically inherited from the above one and both of them ultimately from the rootscope.. See this example http://plnkr.co/edit/TbRJQK?p=preview Also there is a great answer here http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs – PSL Sep 12 '14 at 15:25
  • Yeah, got that. Thanks! – Max Koretskyi Sep 12 '14 at 15:39