使用$ watchCollection时检查更改了哪个范围值

时间:2014-09-20 13:30:50

标签: angularjs angularjs-scope

我的控制器中有很多过滤器。如果其中一个发生了变化,我想调用一个函数。

$scope.$watchCollection("[order, currentFilter, currentPage]", function(newValue, oldValue, scope) {
  if(newValue === oldValue) return;
  $scope.queryModel();
});

但是我想通过在其中添加特定于过滤器的逻辑来使回调变得更复杂:

$scope.$watchCollection("[order, currentFilter, currentPage]", function(newValue, oldValue, scope) {
  if(newValue === oldValue) return;
  $scope.queryModel();
  if(/* order changed */) { /* do stuff */ }
});

所以我的问题是:从回调函数中找出哪个过滤器更改的最优雅的方法是什么?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

如果您不想编写多个if语句,可以执行以下操作:

$scope.$watchCollection("[order, currentFilter, currentPage]", function(newValue, oldValue, scope) {
  if(newValue === oldValue) return;

  var functionMap = {
     order : function () { // do staff for the order filter },
     currentFilter: function () { },
     currentPage : function () { }
  };

  if (newValue)
  {
     functionMap[newValue.filterName]();
  }
});
相关问题