2015-02-08 101 views
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