angularjs - 我可以使用 AngularJS 将多个字段的监视合并到一个监视中吗?

标签 angularjs

AngularJS 有没有办法将其合并到一个 $watch 中,或者我仍然需要一个 $watch 来保存我观看的每件事?

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

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

最佳答案

您可以在下面找到有关如何使用 $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]);
});

Starting from AngularJS 1.3 there's a new method called $watchGroup for observing a set of expressions.

关于angularjs - 我可以使用 AngularJS 将多个字段的监视合并到一个监视中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17872919/

相关文章:

javascript - 全局定义的 AngularJS Controller 和封装

javascript - 使用 ng-click 获取图标表中的位置

javascript - Restify 和 Angular JS 都位于不同的域中,如何使用 Restify 响应设置 httponly cookie?

javascript - Angularjs 确定向用户呈现哪个选项卡(指令)?

javascript - 如何防止 angularJS 抑制脚本错误?

javascript - 添加行时为表格设置动画

angularjs - 在 Angular 单元测试中按类使用 element.find()

javascript - 创建自定义 Angular 智能表

angularjs - 在 AngularJs 中装饰 ng-click 指令

angularjs - 使用 angularjs 和 ui-router,如何禁用一个 View 更改的导航器历史记录