【问题标题】:ngModel with ngSwitch, cannot watch string variables?ngModel 和 ngSwitch,不能看字符串变量?
【发布时间】:2015-06-23 07:14:39
【问题描述】:

我在项目范围内的一些角度变量上使用$scope.$watch 时遇到问题。我制作了一个示例jsfiddle 来说明问题。

基本上,我可以$scope.$watch ng-switch 中的任何模型,只要它是一个对象。如果它是一个字符串,它不会触发监视表达式,并且不会在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); 
    });

【问题讨论】:

    标签: angularjs angularjs-scope ng-repeat ng-switch


    【解决方案1】:

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

    这和你听到“总是在你的 ng-model 中加一个点”时遇到的问题是一样的

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

    【讨论】:

    • 这是正确的答案。始终使用 $scope.someObj.someProp 而不是仅使用 $scope.someProp 以避免内部范围中的变量阴影。
    • 我觉得很害羞...我是 Angular 的新手,那个视频(和文章)很棒。很高兴知道“总是在你的 ng 模型中添加一个点”。
    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 2013-06-23
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多