NgModel with ngSwitch, can't watch string variables?

I'm having trouble using $scope.$watch

for some angular variables that I have in my project scope. I made a sample jsfiddle to illustrate the problem.

Basically, I can use $scope.$watch

any model as ng-switch

long as it is an object. If it is a string, it will not invoke the clock expression and will not be modified outside the scope ng-switch

. angular copies the original string instead of passing it by reference, like an object?

I am using ng-repeat

for some elements - here are some of my code:

<div ng-switch="key">

          <div ng-switch-when="deal_id">
              DEALID: <input type="text" ng-model="dealIdModel"/> -- {{dealIdModel}}
          </div>
          <div ng-switch-when="thing_id">
              THING: <input type="text" ng-model="thingIdModel.test"/> -- {{thingIdModel.test}}
          </div>
          <div ng-switch-default>
              DEFAULT: <input type="text" placeholder="email" ng-model="items.params.email"/> -- {{items.params.email}}
          </div>

        </div>

      

And JS:

$scope.items = {
        "statusCode":"ACTIVE",
        "params":{
          "deal_id":"",
          "thing_id":"",
            "email":"Change me! I will get called"
        }
    };

    $scope.dealIdModel = "I won't change outside of the loop or get called.";
    $scope.thingIdModel = {test:'Change me! So will I!'};

    $scope.$watch('items.params.email', function (now, then, scope) {
        console.log('email change', now, then);
    });

    $scope.$watch('thingIdModel.test', function(now, then, scope) {
       console.log('changed the thing', now, then);   
    });

    $scope.$watch('dealIdModel', function(now, then, scope) {
        console.log('dealID changed:', now, then); 
    });

      

+3


source to share


1 answer


This is because the content area is being created ng-repeat

. Since a new scope is created, if you set an equal variable in the scope of the child objects, you change the reference there, but not in the parent. When you use an object, the parent maintains a reference to the object and only the inner part changes.

This is the same problem as when you hear "always dot your ng model"



More details here: https://github.com/angular/angular.js/wiki/Understanding-Scopes

+3


source







All Articles