ManOfSteele
ManOfSteele

Reputation: 279

Overwriting $scope in controller will not reflect in the DOM

I am trying to persist the whole scope to a service so that it is available and already set up after user navigates away and then returns to the screen.

I have created a service and am storing the current scope there. Later I set the $scope variable passed into the controller with the one stored in my service, but the after inspecting the DOM, I see that it's bound scope is still the scope object that existed before replacing.

How can I replace the scope so that it will also be used for the DOM elements?

Thanks for any help!

the below code tries to see if the local scope variable is initialized and if so it sets the $scope to it, otherwise it continues and wires it all up normally. this.scope is a member variable defined and set in the controller's super class (not shown).

function xyzController($scope, stateService) {
    _super.call(this, $scope, stateService);                    
    if (this.scope.hasBeenInitialized) {
        $scope = this.scope;  // $scope is updated but the DOM's scope never changed
        return;
    }

    $scope.hasBeenInitialized = true;

    ...                
}

Upvotes: 1

Views: 1258

Answers (2)

Hector Virgen
Hector Virgen

Reputation: 169

You could try:

if (this.scope.hasBeenInitialized) {
    angular.extend($scope, this.scope);
    return;
}

This would merge the values from this.scope onto your $scope without replacing the variable.

Upvotes: 2

jpsimons
jpsimons

Reputation: 28090

This won't work. Scope is wired up deep inside Angular. To give you an idea, on any element, you can call:

angular.element(someDomElement).scope();

And get its scope. It's really not do-able to replace scopes like you're trying to do. But the more immediate problem is you're just overwriting that particular variable. It's an object passed in. Imagine you have this code:

var myObject = { a: 1 };
function f(obj) {
  obj = { a: 2 };
}
f(myObject);

Clearly this doesn't change myObject. It'll replace obj within your function, but the thing about scopes is they're set up for you for all the expression in your views (it's the this in any scope functions for example). You'd need to change it through and through, and I don't see a way to do that.

Upvotes: 0

Related Questions