有没有办法可以组合多个AngularJS手表?

时间:2014-03-18 04:52:28

标签: angularjs

我有这个:

        $scope.$watch('option.sCreatedBy', function (newValue, oldValue) {
            if (newValue && newValue !== oldValue) {
                _u.oyc.put('sCreatedBy', newValue);
                $scope.grid.data = null;
            }
        });

        $scope.$watch('option.sModifiedBy', function (newValue, oldValue) {
            if (newValue && newValue !== oldValue) {
                _u.oyc.put('sModifiedBy', newValue);
                $scope.grid.data = null;
            }
        });

所有这些功能都相同,加上我上面没有展示的功能。

有没有办法可以将这些手表组合成一只手表,同时观看/修改多件事?

1 个答案:

答案 0 :(得分:3)

现在,您正在创建两个相同的匿名函数,然后将它们传递给每个$watch方法。第二个参数只是一个回调函数,所以你也可以只命名回调函数并传递引用。

var watchCallback = function (newValue, oldValue) {
    if (newValue && newValue !== oldValue) {
        _u.oyc.put('sCreatedBy', newValue);
        $scope.grid.data = null;
    };
};
$scope.$watch('option.sCreatedBy', watchCallback);
$scope.$watch('option.sModifiedBy', watchCallback);

另一种,也许更多的Angular-ish方法是使用$watchCollection代替$watch

$scope.$watchCollection('[option.sCreatedBy, option.sModifiedBy]', function (newValue, oldValue) {
    if (newValue && newValue !== oldValue) {
        _u.oyc.put('sCreatedBy', newValue);
        $scope.grid.data = null;
    };
});

重要的是要注意$watchCollection的第一个参数不是数组,而是一个字符串看起来像一样。