我的控制器中有这个data
$scope.data = {
home: {
baseValue: "1",
name: "home"
},
contact: {
baseValue: "2",
name: "contract"
}
// a lot more options
};
其中的一些html如下所示:
<section class="content row" ng-repeat="item in data">
{{item.name}}
....
</section>
现在,我想知道什么时候数据改变了,但是因为我在baseValue
变量中使用了对象,所以我不能以一种更简单的方式来watch
属性。
我已经尝试过这样的方法,但我必须循环所有的数组
$scope.$watch('data', function (newValue, oldValue, scope) {
// some code to compare the tow arrays, line by line
}, true);
我如何才能做一个更简单的$watch
,以便只知道baseValue
何时发生更改?
类似的问题:
更新1
我可以为每个对象添加一个单独的监视,以了解baseValue
何时发生更改,但是如果我有一个n
数量的对象,而不是像本例中那样只有几个对象,那就不好了
$scope.$watch('data.home', function (newValue, oldValue, scope) {
// do some stuff with newvalue.baseValue
}, true);
$scope.$watch('data.contact', function (newValue, oldValue, scope) {
// do some stuff with newvalue.baseValue
}, true);
... // Adds more individual `watch`
发布于 2014-07-22 08:53:35
根据您的问题,您可以使用ngChange查看baseValue
的变化并触发函数。
HTML
<section class="content row" ng-repeat="item in data">
Name: {{item.name}} <br/>
BaseValue: <input type="text" ng-model="item.baseValue" ng-change="baseValueChange(item.baseValue)"/>
</section>
控制器
$scope.baseValueChange = function(baseValue) {
console.log("base value change", baseValue);
}
如果你有一个更复杂的版本,可以得到oldValue和newValue,你可以参考这个项目to http://plnkr.co/edit/hqWRG13gzT9H5hxmOIkO?p=preview
HTML
<section class="content row" ng-repeat="item in data">
Name: {{item.name}} <br/>
BaseValue: <input type="text" ng-init="item.oldBaseValue = item.baseValue" ng-model="item.baseValue" ng-change="baseValueChange(item.oldBaseValue, item.baseValue); item.oldBaseValue = item.baseValue"/>
</section>
控制器
$scope.baseValueChange = function(oldVal, newVal) {
console.log("base value change", oldVal, newVal);
}
发布于 2014-07-22 08:30:02
您可以查看对象属性。
所以你可以像这样做
for(var key in $scope.data) {
if($scope.data.hasOwnProperty(key)) {
$scope.$watch("data['" + key + "'].baseValue", function(val, oldVal) {
// Do stuff
});
}
}
没有经过测试,但想法很简单。
发布于 2016-12-21 18:46:34
在这种情况下,无法避免使用多个监视,另一种方法是利用$watchCollection
监视对象值的数组,您可以使用Object.values
函数获得此数组。
scope.$watchCollection(function() {
return Object.values(obj);
}, function(newValues, oldValues) {
// now you are watching all the values for changes!
// if you want to fire a callback with the object as an argument:
if (angular.isFunction(scope.callback())) {
scope.callback()(obj);
}
});
https://stackoverflow.com/questions/24876944
复制相似问题