带有 ngSwitch 的 ngModel,无法观察字符串变量?

ngModel with ngSwitch, cannot watch string variables?

我在对项目范围内的某些 angular 变量使用 $scope.$watch 时遇到问题。我做了一个示例 jsfiddle 来说明这个问题。

基本上,我可以 $scope.$watch ng-switch 中的任何模型,只要它是一个对象。如果它是一个字符串,它不会触发 watch 表达式,并且不会在 ng-switch 区域范围之外被更改。 Angular 是否复制原始字符串而不是像对象一样通过引用传递它?

我在某些元素上使用 ng-repeat -- 这是我的一些代码:

<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>

和 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); 
    });

这与 ng-repeat 创建的子作用域有关。由于创建了一个新作用域,如果您在子作用域上设置一个普通变量,您将更改那里的引用,而不是在父作用域中。当您使用一个对象时,父对象会保留对该对象的引用,只有内部部分会发生变化。

这与您听到 "always put a dot in your ng-model"

时的问题相同

这里有更多详细信息: https://github.com/angular/angular.js/wiki/Understanding-Scopes