3

我在使用$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); 
    });
4

1 回答 1

3

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

这与您听到“总是在您的 ng-model 中添加一个点”时出现的问题相同

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

于 2015-04-16T17:54:33.450 回答