如何$观看角度的多个变量的变化 [英] How to $watch multiple variable change in angular

查看:164
本文介绍了如何$观看角度的多个变量的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何 $范围。$观看角多个变量,并触发回调时,其中一人已经改变了。

  $ scope.name = ...
$ scope.age = ...
$范围。$表(???,函数(){
    //调用时的名称或更改年龄
})


解决方案

更新

角现在提供两种方法的范围 $ watchGroup (自1.3)和<一个href=\"https://docs.angularjs.org/api/ng/type/%24rootScope.Scope#%24watchCollection\">$watchCollection.那些已经被@blazemonger和@kargold提及。


这应该工作独立于类型和值:

  $ $范围手表('[年龄,姓名]',函数(){...},真正的);

您必须设置第三个参数为true,在这种情况下。

字符串连接年龄+名将在这样的情况下失败:

 &LT;按钮NG-的init =年龄= 42;名称='富'NG点击=年龄= 4;名称='2foo'&gt;点击&LT; /按钮&GT;

用户点击之前该按钮观看价值将是 42foo 42 + )和后点击 42foo 4 + 2foo )。因此,手表的功能不会被调用。因此,更好地使用数组前pression如果你不能保证,那这样的情况将不会出现。

 &LT;!DOCTYPE HTML&GT;
&LT; HTML和GT;
    &LT; HEAD&GT;
        &LT;间的charset =UTF-8&GT;
        &LT;链接HREF =// cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css的rel =stylesheet属性/&GT;
        &LT;脚本的src =// cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js\"></script>
        &LT;脚本的src =// cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js\"></script>
        &所述; SCRIPT SRC =HTTP://$c$c.angularjs.org/1.2.0-rc.2/angular.js&GT;&下; /脚本&GT;
        &所述; SCRIPT SRC =HTTP://$c$c.angularjs.org/1.2.0-rc.2/angular-mocks.js&GT;&下; /脚本&GT;
        &LT;脚本&GT;angular.module('示范',[])。控制器('MainCtrl',函数($范围){    $ scope.firstWatchFunctionCounter = 0;
    $ scope.secondWatchFunctionCounter = 0;    。$ $范围手表('[年龄,姓名]',函数(){$ scope.firstWatchFunctionCounter ++;},真正的);
    。$ $范围手表(年龄+名',函数(){$ scope.secondWatchFunctionCounter ++;});
});描述(演示模块',函数(){
    beforeEach(模块('示范'));
    描述(MainCtrl',函数(){
        它('表函数应该增加一个计数器,注入(函数($控制器,$ rootScope){
            VAR范围= $ rootScope $新的()。
            scope.age = 42;
            scope.name ='富';
            VAR CTRL = $控制器('MainCtrl',{'$范围:范围});
            范围$摘要()。            期待(scope.firstWatchFunctionCounter).to​​Be(1);
            期待(scope.secondWatchFunctionCounter).to​​Be(1);            scope.age = 4;
            scope.name ='2foo';
            范围$摘要()。            期待(scope.firstWatchFunctionCounter).to​​Be(2);
            期待(scope.secondWatchFunctionCounter).to​​Be(2); //这将失败!
        }));
    });
});
(函数(){
    变种jasmineEnv = jasmine.getEnv();
    VAR htmlReporter =新jasmine.HtmlReporter();
    jasmineEnv.addReporter(htmlReporter);
    jasmineEnv.specFilter =功能(SPEC){
        返回htmlReporter.specFilter(规范);
    };
    VAR currentWindowOnload =的window.onload;
    在window.onload =函数(){
        如果(currentWindowOnload){
            currentWindowOnload();
        }
        execJasmine();
    };
    功能execJasmine(){
        jasmineEnv.execute();
    }
})();        &LT; / SCRIPT&GT;
    &LT; /头&GT;
    &LT;身体GT;&LT; /身体GT;
&LT; / HTML&GT;

<一个href=\"http://plnkr.co/edit/2DwCOftQTltWFbEDiDlA?p=$p$pview\">http://plnkr.co/edit/2DwCOftQTltWFbEDiDlA?p=$p$pview

PS:

作为评论由@reblace说明,但当然也可以访问的值:

  $范围。手表$('[年龄,姓名]',功能(为newValue,属性oldValue){
    变种NEWAGE =为newValue [0];
    变种了newName =为newValue [1];
    变种oldAge =属性oldValue [0];
    变种使用oldName =属性oldValue [1];
},真正的);

How to $scope.$watch multiple variables in Angular, and trigger callback when one of them has changed.

$scope.name = ...
$scope.age = ...
$scope.$watch('???',function(){
    //called when name or age changed
})

解决方案


UPDATE

Angular offers now the two scope methods $watchGroup (since 1.3) and $watchCollection. Those have been mentioned by @blazemonger and @kargold.


This should work independent of the types and values:

$scope.$watch('[age,name]', function () { ... }, true);

You have to set the third parameter to true in this case.

The string concatenation 'age + name' will fail in a case like this:

<button ng-init="age=42;name='foo'" ng-click="age=4;name='2foo'">click</button>

Before the user clicks the button the watched value would be 42foo (42 + foo) and after the click 42foo (4 + 2foo). So the watch function would not be called. So better use an array expression if you cannot ensure, that such a case will not appear.

<!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, name]', 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:

As stated by @reblace in a comment, it is of course possible to access the values:

$scope.$watch('[age,name]', function (newValue, oldValue) {
    var newAge  = newValue[0];
    var newName = newValue[1];
    var oldAge  = oldValue[0];
    var oldName = oldValue[1];
}, true);

这篇关于如何$观看角度的多个变量的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆