簡體   English   中英

在angular中的指令的多個屬性上設置觀察器

[英]Setting watcher on multiple attributes of directive in angular

我試圖在指令中的多個屬性上設置通用監視程序。 我的代碼如下

.directive('myDirective', function () {
        return {
            restrict: 'A',
            scope: true,
            link: function ($scope, element, attrs) {
                $scope.$watch(function () {
                    return [attrs.attrOne];
                }, function (newVal) {
                   console.log(newVal);
                }, true);

    })

但這不起作用,我已經將對象相等的第三個參數設置為true。 但是,如果我嘗試僅對單個屬性設置觀察者,則它可以正常工作,並且代碼如下所示

.directive('myDirective', function () {
        return {
            restrict: 'A',
            scope: true,
            link: function ($scope, element, attrs) {
               $scope.$watch(attrs.attrOne,
               function (newVal) {
                 console.log(newVal);
                });
        });

誰能詳細解釋一下,為什么會這樣呢?

從AngularJS 1.3開始,有一個名為$ watchGroup的新方法用於觀察一組表達式。

$scope.foo = 'foo';
$scope.bar = 'bar';

$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
  // newValues array contains the current values of the watch expressions
  // with the indexes matching those of the watchExpression array
  // i.e.
  // newValues[0] -> $scope.foo 
  // and 
  // newValues[1] -> $scope.bar 
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM