mohsinali1317
mohsinali1317

Reputation: 4425

angular scope not updating in watcher

I have a watch and in that watch I check for some value and then update the other one. This is my code

 scope.$watch(function () {
 return userfactory.getUser();
 }, function (newValue, oldValue) {
 if (newValue.User) {


     scope.domainuser = newValue.User.DomainUser;
     scope.isGuardian = scope.domainuser.Category === 'Guardian';

     if (scope.isGuardian && scope.mymessage !== undefined) {
         angular.forEach(newValue.User.DependantUsers, function (value, key) {
             if (scope.mymessage.OnBehalfOf === value.DomainUser.UserName) {
                 scope.mymessage.backGround = globalColorsArray[key];

                 console.log(scope.mymessage);

             }


         });
     }
 }
 });

mymessage is passed from where the directive is called. If I have a function lets say a click button and there if I update the value it does update it.

The strange this is that the console log has the updated property in it. But on the template it doesn't get it.

My template has a lot of stuff but the issue is here

<span class="parent-child-color-scheme" ng-show="isGuardian" ng-class="mymessage.backGround"></span>

Apparently if I try to update any property it doesn't work inside the watch. It doesn't take effect.

This is what I have in the directive

return {
        restrict: 'E',
        scope: {
            mymessage: "=message",
            frontpage: "=",
            inbox: "="
        }, controller: function ($scope) {

Upvotes: 1

Views: 35

Answers (1)

Ovidiu Dolha
Ovidiu Dolha

Reputation: 5413

It appeared your scope inside the watch function was referring to a different one than the template's.

If you use the full parameter list of the watch's listener function (as explained here), you can make sure the right scope is used:

scope.$watch(function () {
  return userfactory.getUser();
}, function (newValue, oldValue, scope) {
  ...

To avoid shadowing with your param name you could even use a different name, e.g:

}, function (newValue, oldValue, wScope) {
  ...
  wScope.mymessage.backGround = globalColorsArray[key];

Upvotes: 1

Related Questions