Haocheng
Haocheng

Reputation: 1343

$scope.$watch on some part of object in array

There is an array as below, which stores a mixture of data and styles in it.

User is able to add, remove or re-order its elements, as well as modify value of elements, so I need to watch it with $scope.$watch to do something if it's modified.

However, I don't want to get notified if only its style changes. Is there any better practice to arrange my data, to get notified only if value is changed, thank you.

Plunker

[{
  value: 1,
  selected: true,
  width: '100px'
}, {
  value: 2,
  width: '150px'
}, {
  value: 3,
  width: '100px'
}];

Upvotes: 1

Views: 130

Answers (2)

Bharat
Bharat

Reputation: 943

This is an example to watch only when style changes.

http://plnkr.co/edit/GAG40qBkD4eq3GbKBMhc?p=preview

$scope.$watch(function($scope) {
    return $scope.data.
    map(function(data) {
        return data.width;
    });
}, function(newValue) {
    console.log('Modified width' + newValue);
}, true);

I think similarly you will have to create watch on needed attributes.

Source: http://blogs.microsoft.co.il/choroshin/2014/03/26/angularjs-watch-for-changes-in-specific-object-property/

Upvotes: 1

dieuvn3b
dieuvn3b

Reputation: 6114

Call $watch with true as the third argument:

 $scope.$watch('data', function(newValue, oldValue) {
    console.log(newValue, oldValue);
  },true);

Upvotes: 0

Related Questions