gpt4 book ai didi

javascript - angularJS scope.$watch 整个对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:45:30 25 4
gpt4 key购买 nike

是否可以在 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';
});
}
}
}]);

最佳答案

要看整个物体,需要用到deep watch。这需要第三个参数来观察,因为 true...

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

检查此更新 plunker link

关于javascript - angularJS scope.$watch 整个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28396928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com