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
?
類似の質問:
- AngularJS はデータ変更のオブジェクト配列を監視します
- AngularJS で変更されたオブジェクトを取得するにはどうすればいいですか?
- AngularJS で配列を詳細に監視するにはどうすればよいでしょうか?
アップデート1
各オブジェクトに個別のウォッチを追加して、変更されたことを知ることもできますが、この例のようにオブジェクトが2、3個だけではなく、複数のオブジェクト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`
ベストアンサー1
質問に基づいて、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を取得できるより洗練されたバージョンが必要な場合は、この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);
}