angularJS范围。$ watch整个对象

时间:2015-02-08 17:21:41

标签: javascript angularjs angularjs-directive angularjs-scope

是否可以在angularJS中观看整个对象?

我创建了一个向上显示我的意思的plunker: http://plnkr.co/edit/QxLzbwKkJ5k50DiP8OP1

当我更改R G或B值时,colors对象不会触发更改事件,仅触发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';
            });
        }
    }
}]);

1 个答案:

答案 0 :(得分:4)

观看整个物体,需要使用深度观察。这需要第三个参数来观察,真实...

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

检查此更新的plunker link