1

$scope.$watch を介して削除または追加されたアイテムを検出する方法はありますか?

以下の例を参照してください。

var data = [{id: 1}, {id: 2}, {id: 3}];

$scope.$watch(function () {return data}, function (newValue, oldValue) {
    console.log(newValue, oldValue);
    // I want to detect removing or adding here:
    // var removedItem = ...?
    // var addedItem = ...?
}, true)

data.push({id: 4});
data.splice(0, 1);

ありがとう

4

4 に答える 4

1

このコードは私にとってはうまくいきます

x = []

$rootScope.$watch((-> x), (newValue, oldValue) ->

    changed = newValue.filter((item, index) ->
        return oldValue[index] and angular.equals(item, oldValue[index]) is no
    )
    added = newValue.filter((item, index) ->
        return not oldValue[index]
    )
    removed = oldValue.filter((item, index) ->
        return not newValue[index]
    )
    console.log('x', changed, added, removed)
, yes)
于 2015-03-17T16:59:34.283 に答える
0

これを達成するための直接的な方法はありません。おそらく、結果には以下を使用できます。

// newValue を表示します。var diff = $(newValue).not(oldValue).get();

//oldValue を表示します。var diff = $(oldValue).not(newValue).get();

于 2015-03-17T16:21:23.197 に答える
0

使用できます$watchCollection

ドキュメントから:

[...] コレクションは標準$watch操作で観察され、すべての呼び出しで調べられて$digest()、アイテムが追加、削除、または移動されたかどうかが確認されます。

于 2015-03-17T16:40:58.050 に答える