AngularJSはオブジェクト配列内のオブジェクトプロパティを監視します 質問する

AngularJSはオブジェクト配列内のオブジェクトプロパティを監視します 質問する

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

各オブジェクトに個別のウォッチを追加して、変更されたことを知ることもできますが、この例のようにオブジェクトが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);
}

おすすめ記事