How to access/update $rootScope from outside Angular

假如想象 提交于 2019-11-26 09:32:50

问题


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);

回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/24595460/how-to-access-update-rootscope-from-outside-angular

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