【问题标题】:Can I combine watching of multiple fields into one watch with AngularJS? [duplicate]我可以使用 AngularJS 将多个字段的观看合并到一个手表中吗? [复制]
【发布时间】:2026-01-03 03:40:01
【问题描述】:

在 AngularJS 中有没有办法将它组合到一个 $watch 中,还是我仍然需要一个 $watch 来为我观看的每一件事?

    $scope.$watch('option.selectedContentType', function () {
        $scope.getData();
    });

    $scope.$watch('option.selectedContentStatus', function () {
        $scope.getData();
    });

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    如果你使用 angular 1.1.4,你可以使用$watchCollection,这里是文档中示例代码中的代码 sn-p。

    $scope.names = ['igor', 'matias', 'misko', 'james'];
    
    $scope.$watchCollection('names', function(newNames, oldNames) {
      $scope.dataCount = newNames.length;
    });
    

    【讨论】:

    • -1:这不是 OP 要求的。你的 sn-p 监视 '$scope.names' 的变化。请仔细检查问题。他想把多个类似的手表“打包”成一个手表表情。 dluz 的最后一个片段(观察范围变量列表)是最接近的,因为它是一个可以“观察”两个范围变量的表达式。
    【解决方案2】:

    您可以在下面找到有关如何使用 $watchCollection 的一些变体

    http://jsbin.com/IYofiPi/4 - working example here.

    检查您的 console.log 以查看被触发的事件。

    观察数组中的项目

    $scope.cities = ['Salvador', 'London', 'Zurich', 'Rio de Janeiro']; //Array
    
    $scope.$watchCollection('cities', function(newValues, oldValues) {
      console.log('*** Watched has been fired. ***');
      console.log('New Names :', newValues);
    });
    

    观察对象的属性

    $scope.city = {
      name: 'London',
      country: 'England',
      population: 8.174
    }
    
    $scope.$watchCollection('city', function(newValues, oldValues) {
      console.log('*** Watched has been fired. ***');
      console.log('New Names :', newValues);
    });
    

    查看范围变量列表($scope.firstPlanet、$scope.secondPlanet)

    $scope.firstPlanet = 'Earth';
    $scope.secondPlanet = 'Mars';
    
    $scope.$watchCollection('[firstPlanet, secondPlanet]', function(newValues){
      console.log('*** Watched has been fired. ***');
      console.log('New Planets :', newValues[0], newValues[1]);
    });
    

    从 AngularJS 1.3 开始,有一个名为 $watchGroup 的新方法用于观察一组表达式。

    【讨论】:

    • +1:最后一个片段是 OP 要求的。很酷的技巧,似乎有效。
    • 顺便说一句。还有watchGroup:*.com/questions/11952579/…
    • 酷!很高兴知道@quetzalcoatl!我也会在这里更新我的答案。干杯
    最近更新 更多