How to access/update $rootScope from outside Angular

我的未来我决定 提交于 2019-11-26 20:20:30

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 :(';
  });
}

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!