4

是否可以在angularJS中觀察整個對象?

我創建了一個plunker向你展示我的意思: http://plnkr.co/edit/QxLzbwKkJ5k50DiP8OP1

當我改變R G或B值的顏色對象將不會觸發更改事件,只有R G或B值火災。 我可以自己發動一個事件,以便我知道整個對象改變了嗎?

而且這裏的plunker是代碼:

function ColorObject() 
{ 
    this.r = 0; 
    this.g = 0; 
    this.b = 0; 

    this.c = 0; 
    this.m = 0; 
    this.y = 0; 
    this.k = 0; 

    this.hex = "#ff0000"; 
    this.oppositeHex = "#00ffff"; 
} 

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

chColorChanger.controller('chColorChangerCtrl', function ($scope,$document,$element) 
{  
    $scope.colors = new ColorObject(); 
    $scope.gMessage = 0; 
    $scope.message = 'scope initialized'; 
}); 

chColorChanger.directive('chColorValue',['$document',function($document) { 
    return { 
     link: function (scope, elem, attrs) { 

      scope.$watch('colors',function(newValue,oldValue){ 
       scope.gMessage++; 
      }); 

      scope.$watch('colors.r', function (newValue,oldValue) { 
       scope.message = 'r changed'; 
      }); 

      scope.$watch('colors.g', function (newValue,oldValue) { 
       scope.message = 'g changed'; 
      }); 

      scope.$watch('colors.b', function (newValue,oldValue) { 
       scope.message = 'b changed'; 
      }); 
     } 
    } 
}]); 

回答

4

觀看整個對象,你需要使用深手錶。這就需要第三個參數看,作爲真正...

 scope.$watch('colors',function(newValue,oldValue){ 
      scope.gMessage++; 
     }, true); 

入住此更新plunker link