使用$ watchGroup的多个变量

时间:2016-07-04 15:13:14

标签: javascript angularjs angularjs-directive

我的watchgroup不工作,它给了我undefined,我在代码中做错了什么?

 $scope.$watchGroup([vm.footer.nrRows, vm.isSaved], function(current, original) {

            console.log("Nr Rows "+current[0]);
            console.log("is saved? "+current[1]);
        });

3 个答案:

答案 0 :(得分:1)

将您的代码更改为:

$scope.$watchGroup(["vm.footer.nrRows", "vm.isSaved"], function() {
   ...
}, true);

如果您的变量为$scope.something,则应加入$ watch "something"

答案 1 :(得分:0)

这是一个代码片段:



var app = angular.module('app', []);

app.controller('mainCtrl', function ($scope) {
  $scope.footer = {};
  $scope.footer.nrRows = 5;
  $scope.isSaved = true;
  $scope.$watchGroup(['footer.nrRows', 'isSaved'], function(newValues, oldValues, scope) {
    console.log(oldValues);
    console.log(newValues);
  });
});

<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>      
</head>

<body ng-controller="mainCtrl">
  <input ng-model="footer.nrRows" />
  <span ng-bind="footer.nrRows"></span>
  <hr />
  <input ng-model="isSaved" />
  <span ng-bind="isSaved"></span>
</body>

</html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我找到了这个解决方案,但仍然无法弄清楚与上述其他解决方案相比有什么不同,只有上述解决方案对我有用。希望有人向我解释原因。

解决方案:

 $scope.$watchGroup([
            function(){
                return vm.footer.nrRows;
            }, function(){
                return vm.isSaved;
            }
        ], function(newValues, oldValues){
            var newProp1 = newValues[0];
            var newProp2 = newValues[1];
            console.log("newProp1");
            console.log(newProp1);
            console.log("newProp2");
            console.log(newProp2);
        });