angularJS scope.$watch 整个对象
angularJS scope.$watch whole object
是否可以在 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
是否可以在 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