1

In angularJs: what's the different between setting $watch on string variable and setting $watch on Object's key?

The detail scenario is as follow:

$scope.activedMenu = {'id' : '...', 'name' : 'menu1'};
$scope.selectedMenuName = 'menu1';
$scope.$watch('activedMenu.name', function () {...});
$scope.$watch('selectedMenuName', function () {...});

So, my question is what's the different between "$scope.$watch('activedMenu.name', function () {...})" with "$scope.$watch('selectedMenuName', function () {...})"? Any help will be appreciated!

(I think these two ways to set a $watch are equivalence, I refer from the scope develop guide! https://docs.angularjs.org/guide/scope)

1
  • you seem to be confused. both $watch statements are identical other than the parameter they are watching; and in your case, selectedMenuName and activatedMenu.name aren't even the same object, so the obvious difference here is the data they are monitoring. Commented Apr 27, 2015 at 3:36

1 Answer 1

1

Basically $watch need string parameter & search for that parameter inside current scope & placed dirty watch on it.

Watching on activedMenu.name OR selectedMenuName is one as the same thing, 1st one will watch on name property of activedMenu, the 2nd one will watch on selectedMenuName scope variable.

The only difference I think is you are watching on single property so you can use object equality option here which deep watches the object change. It could be possible for you 1st watch but watch string should be activedMenu only

$scope.$watch('activedMenu', function(newVal, oldVal){
   //on watch code here
}, true);
Sign up to request clarification or add additional context in comments.

2 Comments

When you use the deep watch way, It's most expensive. So, I prefer Watching by reference way.
@bill I just gave an example, not preferring to use deep watch..just for explaination

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.