我可以将使用AngularJS将多个视野合并到一个手表中吗?

23 angularjs

AngularJS中是否有一种方法可以将它组合成一个$ watch或者我仍然需要为我观看的每个东西都有一个$ watch?

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

    $scope.$watch('option.selectedContentStatus', function () {
        $scope.getData();
    });
Run Code Online (Sandbox Code Playgroud)

Den*_*Luz 43

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

http://jsbin.com/IYofiPi/4 - 这里的工作示例.

检查您的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);
});
Run Code Online (Sandbox Code Playgroud)

观察对象的属性

$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);
});
Run Code Online (Sandbox Code Playgroud)

查看范围变量列表($ 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]);
});
Run Code Online (Sandbox Code Playgroud)

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

  • 顺便说一句 还有watchGroup:http://stackoverflow.com/questions/11952579/watch-multiple-scope-attributes-in-angularjs (3认同)

zs2*_*020 1

如果您使用 Angular 1.1.4,则可以使用$watchCollection,这里是文档中示例代码的代码片段。

$scope.names = ['igor', 'matias', 'misko', 'james'];

$scope.$watchCollection('names', function(newNames, oldNames) {
  $scope.dataCount = newNames.length;
});
Run Code Online (Sandbox Code Playgroud)