How to access/update $rootScope from outside Angular

后端 未结 3 1016
半阙折子戏
半阙折子戏 2020-11-29 04:13

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

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

myApp.run(function ($rootScope) {
    $ro         


        
相关标签:
3条回答
  • 2020-11-29 04:35

    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

    0 讨论(0)
  • 2020-11-29 04:43

    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.

    0 讨论(0)
  • 2020-11-29 04:46

    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 :(';
      });
    }
    
    0 讨论(0)
提交回复
热议问题