0

I want to watch over one of $rootScope variable.

It works and update bar when I explicitly register a watcher:

$rootScope.$watch('foo', function(newVal) {
  $scope.bar = newVal;
});

But it does not update when I just assign bar to $rootScope's foo. Shouldn't it implicitly assign a watcher for this expression?

$scope.bar = $rootScope.foo;

By the way, foo is initially an empty object, and it is updated to {'test': 'something'} later.

UPDATE

It is now clear that this expression won't assign a watcher and update itself. So, is there any way to update bar without a watch function in controller?

Are promises available for this purpose? I think Restangular can do it like this:

$scope.list = Restangular.all('accounts').getList().$object;
2
  • 1
    nope. thats just an assignment. Commented Nov 14, 2014 at 13:04
  • yes, it appears this was a silly question :) I updated my question. Commented Nov 14, 2014 at 13:18

1 Answer 1

3

No because that's not how javascript works. If you tried something like this outside of angular, you would see nothing would update:

var temp = 4;
var temp2 = temp;

temp = 5;
console.log(temp2); //outputs 4

The reason it does work for other things (such as objects) is because they are referenced. This example would work:

var temp = { value: 4 };
var temp2 = temp;

temp.value = 5;
console.log(temp2); //outputs { value: 5 }

Edit

Without seeing the rest of your code and based off your comment, i'm going to assume you destroyed your reference. While my example above would work, this one won't:

var temp = { value: 4 };
var temp2 = temp;

temp = { value: 5 };
console.log(temp2); //outputs { value: 4 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Mathew, but my foo was an object actually. It's initial value is {}, and updated value is {'label': 'test'}. I updated my question anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.