How to access/update $rootScope from outside Angular
Asked Answered
S

3

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);
Serigraph answered 6/7, 2014 at 11:44 Comment(3)
how is scope being updated? if it is from events outside of angular you need to tell angular to run a digestGarfield
@charlietfl: I tried modifying the root scope inside $apply(), but it doesn't help. I have updated my question to reflect what I tried.Serigraph
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 appGarfield
G
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 :(';
  });
}
Georgia answered 6/7, 2014 at 13:20 Comment(10)
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. :)Polychaete
@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.Georgia
@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 appMercola
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 :)Georgia
This post showed me how to get $rootScope without injecting it when a local scope is available, i.e. $scope.$rootSo
@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 ;)Bibb
For the very, very rare cases, === ninja hacky code, and that's what you both (@Mercola & @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.Halfwit
Access an elements from devtools console is not a rare case!Pregnable
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 <script> that gets run client-side.Ionone
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.Ionone
R
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.

Rigging answered 6/7, 2014 at 12:57 Comment(0)
L
-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

Liva answered 6/7, 2014 at 11:48 Comment(5)
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.Serigraph
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={...}})Liva
Yes, thanks, but Angular ignores my changes. I have updated my question to reflect what I tried.Serigraph
As, solution provided by @ExpertSystem, here's how you access and update rootscope object without a controller: jsfiddle.net/SU3mw/1Liva
This is not what he asked for... He needs to use $rootScope from outside the angular environment.Gotama

© 2022 - 2024 — McMap. All rights reserved.