参见英文答案 >
Watch multiple $scope attributes10个答案如何$ scope。$在Angular中观察多个变量,并且当其中一个更改时触发回调。
$scope.name = ... $scope.age = ... $scope.$watch('???',function(){ //called when name or age changed })
更新
原文链接:https://www.f2er.com/angularjs/146770.htmlAngular现在提供了两个范围方法$watchGroup(自1.3版本)和$watchCollection.这些被@blazemonger和@kargold提及。
这应该独立于类型和值:
$scope.$watch('[age,name]',function () { ... },true);
在这种情况下,必须将第三个参数设置为true。
字符串连接’年龄名称’将失败在这样的情况下:
<button ng-init="age=42;name='foo'" ng-click="age=4;name='2foo'">click</button>
在用户单击按钮之前,观看的值将是42foo(42 foo),然后单击42foo(4 2foo)。所以watch函数不会被调用。所以更好地使用数组表达式,如果你不能确保,这样的情况不会出现。
<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> <link href="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet" /> <script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script> <script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script> <script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script> <script src="http://code.angularjs.org/1.2.0-rc.2/angular-mocks.js"></script> <script> angular.module('demo',[]).controller('MainCtrl',function ($scope) { $scope.firstWatchFunctionCounter = 0; $scope.secondWatchFunctionCounter = 0; $scope.$watch('[age,function () { $scope.firstWatchFunctionCounter++; },true); $scope.$watch('age + name',function () { $scope.secondWatchFunctionCounter++; }); }); describe('Demo module',function () { beforeEach(module('demo')); describe('MainCtrl',function () { it('watch function should increment a counter',inject(function ($controller,$rootScope) { var scope = $rootScope.$new(); scope.age = 42; scope.name = 'foo'; var ctrl = $controller('MainCtrl',{ '$scope': scope }); scope.$digest(); expect(scope.firstWatchFunctionCounter).toBe(1); expect(scope.secondWatchFunctionCounter).toBe(1); scope.age = 4; scope.name = '2foo'; scope.$digest(); expect(scope.firstWatchFunctionCounter).toBe(2); expect(scope.secondWatchFunctionCounter).toBe(2); // This will fail! })); }); }); (function () { var jasmineEnv = jasmine.getEnv(); var htmlReporter = new jasmine.HtmlReporter(); jasmineEnv.addReporter(htmlReporter); jasmineEnv.specFilter = function (spec) { return htmlReporter.specFilter(spec); }; var currentWindowOnload = window.onload; window.onload = function() { if (currentWindowOnload) { currentWindowOnload(); } execJasmine(); }; function execJasmine() { jasmineEnv.execute(); } })(); </script> </head> <body></body> </html>
http://plnkr.co/edit/2DwCOftQTltWFbEDiDlA?p=preview
PS:
如@reblace在注释中所述,当然可以访问这些值:
$scope.$watch('[age,function (newValue,oldValue) { var newAge = newValue[0]; var newName = newValue[1]; var oldAge = oldValue[0]; var oldName = oldValue[1]; },true);