43

My application initializes an object graph in $rootScope, like this ...

var myApp = angular.module('myApp', []);

myApp.run(function ($rootScope) {
    $rootScope.myObject = { value: 1 };
});

... and then consumes data from that object graph (1-way binding only), like this ...

<p>The value is: {{myObject.value}}</p>

This works fine, but if I subsequently (after page rendering has completed) try to update the $rootScope and replace the original object with a new one, it is ignored. I initially assumed that this was because AngularJS keeps a reference to the original object, even though I have replaced it.

However, if I wrap the the consuming HTML in a controller, I am able to repeatedly update its scope in the intended manner and the modifications are correctly reflected in the page.

myApp.controller('MyController', function ($scope, $timeout) {
    $scope.myObject = { value: 3 };

    $timeout(function() {
        $scope.myObject = { value: 4 };

        $timeout(function () {
            $scope.myObject = { value: 5 };
        }, 1000);
    }, 1000);
});

Is there any way to accomplish this via the $rootScope, or can it only be done inside a controller? Also, is there a more recommended pattern for implementing such operations? Specifically, I need a way to replace complete object graphs that are consumed by AngularJS from outside of AngularJS code.

Thanks, in advance, for your suggestions, Tim

Edit: As suggested in comments, I have tried executing the change inside $apply, but it doesn't help:

setTimeout(function() {
    var injector = angular.injector(["ng", "myApp"]);
    var rootScope = injector.get("$rootScope");

    rootScope.$apply(function () {
        rootScope.myObject = { value: 6 };
    });

    console.log("rootScope updated");
}, 5000);
gkalpak
  • 47,844
  • 8
  • 105
  • 118
Tim Coulter
  • 8,705
  • 11
  • 64
  • 95
  • how is scope being updated? if it is from events outside of angular you need to tell angular to run a digest – charlietfl Jul 06 '14 at 12:33
  • @charlietfl: I tried modifying the root scope inside $apply(), but it doesn't help. I have updated my question to reflect what I tried. – Tim Coulter Jul 06 '14 at 12:47
  • suggest you create a demo that replicates the problem. It's not entirely clear why you are only dealing with rootscope only and can't use controllers in your app – charlietfl Jul 06 '14 at 12:56

3 Answers3

94

Except for very, very rare cases or debugging purposes, doing this is just BAD practice (or an indication of BAD application design)!

For the very, very rare cases (or debugging), you can do it like this:

  1. Access an element that you know is part of the app and wrap it as a jqLite/jQuery element.
  2. Get the element's Scope and then the $rootScope by accessing .scope().$root. (There are other ways as well.)
  3. Do whatever you do, but wrap it in $rootScope.$apply(), so Angular will know something is going on and do its magic.

E.g.:

function badPractice() {
  var $body = angular.element(document.body);  // 1
  var $rootScope = $body.scope().$root;        // 2
  $rootScope.$apply(function () {              // 3
    $rootScope.someText = 'This is BAD practice :(';
  });
}

See, also, this short demo.


EDIT

Angular 1.3.x introduced an option to disable debug-info from being attached to DOM elements (including the scope): $compileProvider.debugInfoEnabled()
It is advisable to disable debug-info in production (for performance's sake), which means that the above method would not work any more.

If you just want to debug a live (production) instance, you can call angular.reloadWithDebugInfo(), which will reload the page with debug-info enabled.

Alternatively, you can go with Plan B (accessing the $rootScope through an element's injector):

function badPracticePlanB() {
  var $body = angular.element(document.body);           // 1
  var $rootScope = $body.injector().get('$rootScope');  // 2b
  $rootScope.$apply(function () {                       // 3
    $rootScope.someText = 'This is BAD practice too :(';
  });
}
gkalpak
  • 47,844
  • 8
  • 105
  • 118
  • 6
    This answer would be waaaay more useful to other people aside from OP if you could explain *why* it's a bad practice and show the right way of doing it. :) – temporary_user_name Mar 04 '15 at 20:56
  • @Aerovistae: I can't show the right way of doing it, because there is nothing _right_ about any way of doing it. You just shouldn't do it (unless you are debugging something). The right way, is to do anything you need to do from inside Angular (where you have "proper" access to the `$rootScope`). Reason's range from hurting testability/maintainability/declarativeness to being way more error-prone/difficult to debug/unintuitive etc. – gkalpak Mar 05 '15 at 08:31
  • @ExpertSystem: I'm writing a browser extension that inject vanilla javascript code to page and need to affect the site that written with angularJS. I think that he best approach is to get the rootscope and brodcast angular-event. In this way I don't need to know nothing about the site, except the message name. Thank you for solving the problem although that is bad practice to use it within angular app – RPG Mar 10 '15 at 13:38
  • Since the Angular app itself needs to be aware of the extension, I believe there should be a better (more "Angular") way to do it (e.g. have a directive on an element and emit events on that element or something). But in any case, injecting code from a browser extension into the page might be special case enough to justify accessing the `$rootScope` externally :) – gkalpak Mar 10 '15 at 14:07
  • 1
    This post showed me how to get `$rootScope` without injecting it when a local scope is available, i.e. `$scope.$root` – berto Mar 20 '15 at 20:45
  • @ExpertSystem: My justification for doing this is that I'm migrating an app from plain JS to Angular and I don't want to brake everything at once but do it in a more step-by-step manner ;) – Pawel Gorczynski Jul 16 '15 at 07:31
  • _For the very, very rare cases,_ === _ninja hacky code_, and that's what you both (@RPG & @pawel) are doing. It is justified in very rare cases, and you happened to find 90% of them :D. Anyway, I needed just throw in some code for a directive to chew, and I don't have ATM the whole other stuff I need to make it "right", so this works wonders. Don't worry, it's not going into production. And I really like that `$compileProvider.debugInfoEnabled()`, it'll keep me from messing stuff up. – tfrascaroli Jul 30 '15 at 13:44
  • Access an elements from devtools console is not a rare case! – Pavel Patrin Dec 04 '16 at 15:33
  • This is useful to me because the only way for me to add logic to our partner's code is to insert it into a ` – AaronStPete Dec 24 '19 at 14:59
  • I would also agree this is terrible practice and in my use-case, clearly the cause of several challenges including: large delay between writing code and testing code, getting code to run when I need it to, I'm sure I can find more but I've only been looking at this for a week. – AaronStPete Dec 24 '19 at 15:06
1

After you update the $rootScope call $rootScope.$apply() to update the bindings.

Think of modifying the scopes as an atomic operation and $apply() commits those changes.

Martin
  • 15,820
  • 4
  • 47
  • 56
-2

If you want to update root scope's object, inject $rootScope into your controller:

myApp.controller('MyController', function ($scope, $timeout, $rootScope) {

    $rootScope.myObject = { value: 3 };

    $timeout(function() {

        $rootScope.myObject = { value: 4 };

        $timeout(function () {
            $rootScope.myObject = { value: 5 };
        }, 1000);

    }, 1000);
});

Demo fiddle

Raghavendra
  • 5,281
  • 4
  • 36
  • 51
  • 3
    This is not what I asked for. I asked how to modify the root scope from outside of Angular. My application does not have a controller and, unfortunately, the architecture I am using doesn't allow me to create one. The controller in the above example was just to prove that it is possible to replace a complete object graph and that Angular will act on that change. – Tim Coulter Jul 06 '14 at 12:21
  • 2
    If you want to access root scope out side of controller, use: `var rs = angular.element($('body')).scope();` then use `rs.$apply(function(){rs.myObject={...}})` – Raghavendra Jul 06 '14 at 12:42
  • Yes, thanks, but Angular ignores my changes. I have updated my question to reflect what I tried. – Tim Coulter Jul 06 '14 at 12:48
  • As, solution provided by @ExpertSystem, here's how you access and update rootscope object without a controller: http://jsfiddle.net/SU3mw/1/ – Raghavendra Jul 07 '14 at 12:52
  • This is not what he asked for... He needs to use $rootScope from outside the angular environment. – BenNov Jan 18 '17 at 21:19