AngularJS在对象数组中观察对象属性 [英] AngularJS watch an object property in an object array
问题描述
我的控制器中有数据
$scope.data = {
home: {
baseValue: "1",
name: "home"
},
contact: {
baseValue: "2",
name: "contract"
}
// a lot more options
};
有一些像这样的html:
with some html like this:
<section class="content row" ng-repeat="item in data">
{{item.name}}
....
</section>
现在,我想知道 baseValue
已更改,但由于我在数据变量中使用了一个对象,我无法以更简单的方式监视
该属性。
Now, I want to know when the baseValue
is changed but because of I using a objects inside the data variable I can not watch
the property in a simpler way.
我尝试了类似的东西,但我必须循环所有数组
I have tried something like this, but I have to loop all the array
$scope.$watch('data', function (newValue, oldValue, scope) {
// some code to compare the tow arrays, line by line
}, true);
我如何做一个更简单的 $ watch
仅在 baseValue
更改时才知道?
How can I do a simpler $watch
to know only when the baseValue
is changed?
类似问题:
- AngularJS watch array of objects for data change
- How to get an object that was changed in angularjs?
- How to deep watch an array in angularjs?
更新 1
我可以为每个对象添加一个单独的监视,以了解 baseValue $的时间c $ c>已更改,但如果我有一个
n
个对象数量不会很好,不仅仅是这个例子中的几个对象
I could add an individual watch for each object to know when the baseValue
is changed, but it won't be nice if I had an n
number of objects, not only a couple of objects like in this example
$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`
推荐答案
根据您的问题,您可以使用ngChange观察 baseValue
的更改并触发该功能。
Based on your question, you can use ngChange to watch changes of baseValue
and trigger the function.
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,你可以参考这个plunkr - http://plnkr.co/edit/hqWRG13gzT9H5hxmOIkO?p=preview
If you a more sophisticated version which can get oldValue and newValue, you can refer to this plunkr - 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);
}
这篇关于AngularJS在对象数组中观察对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!