Why can't the $rootScope be accessed in the template of a directive with isolate scope?

90,848

Solution 1

You can try this way out using $root.blah

Working Code

html

 <label ng-click="test($root.blah)">Click</label>

javascript

  angular.module('app', [])
    .controller('Ctrl', function Ctrl1($scope,  $rootScope) {
        $rootScope.blah = 'Hello';
        $scope.yah = 'World'
    })
    .directive('myTemplate', function() {
        return {
            restrict: 'E',
            templateUrl: 'my-template.html',
            scope: {},
            controller: ["$scope", "$rootScope", function($scope, $rootScope) {
                console.log($rootScope.blah);
                console.log($scope.yah);

                $scope.test = function(arg) {
                    console.log(arg);
                }
            }]
        };
    });

Solution 2

Generally, you should avoid using $rootScope to store values you need to share between controllers and directives. It's like using globals in JS. Use a service instead:

A constant (or value ... use is similar):

.constant('blah', 'blah')

https://docs.angularjs.org/api/ng/type/angular.Module

A factory (or service or provider):

.factory('BlahFactory', function() {
    var blah = {
        value: 'blah'
    };

    blah.setValue = function(val) {
      this.value = val;
    };

    blah.getValue = function() {
        return this.value;
    };

    return blah;
})

Here is a fork of your Fiddle demonstrating how you might use either

Solution 3

1) Because of the isolate scope $scope in your controller Ctrl and in the directive controller don't refer to the same scope - let's says we have scope1 in Ctrl and scope2 in directive.

2) Because of the isolate scope scope2 do not prototypicallly inherit from $rootScope ; so if you define $rootScope.blah there is no chance you can see it in scope2.

3) What you can access in your directive template is scope2

If I sum it up, here is the inheritance schema

    _______|______
    |            |
    V            V
$rootScope     scope2
    |
    V
  scope1


$rootScope.blah
> "Hello"
scope1.blah
> "Hello"
scope2.blah
> undefined

Solution 4

I know this an old question. But it didn't satisfy my inquisition about why the isolated scope won't be able to access properties in the $rootscope.

So I dug in the angular lib and found -

$new: function(isolate) {
  var ChildScope,
      child;

  if (isolate) {
    child = new Scope();
    child.$root = this.$root;
    child.$$asyncQueue = this.$$asyncQueue;
    child.$$postDigestQueue = this.$$postDigestQueue;
  } else {

    if (!this.$$childScopeClass) {
      this.$$childScopeClass = function() {
        // blah blah...
      };
      this.$$childScopeClass.prototype = this;
    }
    child = new this.$$childScopeClass();
  }

This is the function called by angular whenever a new scope is created. Here it's clear that any isolated scope is not prototypically inheriting the rootscope. rather only the rootscope is added as a property '$root' in the new scope. So we can only access the properties of rootscope from the $root property in the new isolated scope.

Share:
90,848

Related videos on Youtube

camden_kid
Author by

camden_kid

Camden is the centre of the universe.

Updated on July 05, 2022

Comments

  • camden_kid
    camden_kid about 2 years

    With isolate scope the template of the directive does not seem to be able to access the controller ('Ctrl') $rootScope variable which, however, does appear in the controller of the directive. I understand why the controller ('Ctrl') $scope variable isn't visible in the isolate scope.

    HTML:

    <div ng-app="app">
        <div ng-controller="Ctrl">
            <my-template></my-template>
        </div>
    
        <script type="text/ng-template" id="my-template.html">
            <label ng-click="test(blah)">Click</label>
        </script>
    </div>
    

    JavaScript:

    angular.module('app', [])
        .controller('Ctrl', function Ctrl1($scope,  $rootScope) {
            $rootScope.blah = 'Hello';
            $scope.yah = 'World'
        })
        .directive('myTemplate', function() {
            return {
                restrict: 'E',
                templateUrl: 'my-template.html',
                scope: {},
                controller: ["$scope", "$rootScope", function($scope, $rootScope) {
                    console.log($rootScope.blah);
                    console.log($scope.yah);,
    
                    $scope.test = function(arg) {
                        console.log(arg);
                    }
                }]
            };
        });
    

    JSFiddle

    The variable is accessed with no isolate scope - as can be seen by commenting the isolate scope line:

            // scope: {},
    
    • Marc Kline
      Marc Kline about 10 years
      Have you tried injecting $rootScope into the directive ... directive('myTemplate', function($rootScope) { ... }) ?
    • camden_kid
      camden_kid about 10 years
      @MarcKline Just tried that and no luck.
    • Marc Kline
      Marc Kline about 10 years
    • Marc Kline
      Marc Kline about 10 years
      Is there a reason why using a service is not sufficient for your purposes?
    • camden_kid
      camden_kid about 10 years
      @MarcKline I'm starting to think you may be right and a service is the best way to go.
    • Kalyan
      Kalyan almost 10 years
      camden_kid or Marc (or any one reading this), Can you specify the advantages of one approach over other ($root vs Factory approach I mean)? Why is using factory better?
    • camden_kid
      camden_kid almost 10 years
      @Kalyan - I personally think $rootScope should only be used for events and Factory for passing data to directives. One reason is that using $rootScope is like using global variables which isn't ideal. Also, a Factory can be a well defined wrapper which can be extended at a later date.
  • Marc Kline
    Marc Kline about 10 years
    Very helpful but nidhishkrishnan's workaround does work if somehow using rootScope values is necessary. A nice hack it is.
  • camden_kid
    camden_kid about 10 years
    I'm marking this as the answer as it 'solves' what I wanted to achieve (I didn't know of '$root' or that it could be used like this). However, I would suggest that Mark Kline's answer is generally the best solution.
  • camden_kid
    camden_kid about 10 years
    +1 Thanks very much for this and for pointing me in the correct direction for what I am trying to achieve. I think NidhishKrishnan's should be accepted as the 'answer' for the reason stated in my comment.
  • Farzad Yousefzadeh
    Farzad Yousefzadeh over 8 years
    +1 for the use case of constants as they are rare to be used. Also the note on not using $rootScope was a pro tip.
  • Cris R
    Cris R about 8 years
    amazing! its quite useful to know that the $rootScope changes into $root into the views, thanks a lot!
  • Alfredo A.
    Alfredo A. over 7 years
    This is perfect since what I needed to do was accessing a function defined in the rootScope
  • IsraGab
    IsraGab almost 7 years
    Well, what you said is logic in order to answer why I can't use $rootScope variables in html (without $root.), but when I use the Batarang plug-in to see the $scopes, I can clearly see that $rootScope is the parent $scope of all the others (including isolated scope in directives). Also, the definition from the angular official docs said: "Every application has a single root scope. All other scopes are descendant scopes of the root scope" (docs.angularjs.org/api/ng/service/$rootScope)
  • Unknown_Coder
    Unknown_Coder about 6 years
    Good one. It's working here too. Can you please explain why $root instead of $rootScope? I have also injected $rootScope but it is undefined while function call.