1

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'
}];
2
  • Just to confirm a few things: (1) the only property you want to be notified of changing is value? (2) should the watcher also ignore any shuffling of the order of the data? (3) watcher definitely preferable to ng-change, etc? Commented Jun 23, 2015 at 12:43
  • 1
    @JcT (1) There may be a few values I need to get notified (2) The order of array shouldn't be ignored (3) It may not be from <input>, so I don't think ng-change is applicable. Thanks.. Commented Jun 24, 2015 at 1:07

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

Comments

0

Call $watch with true as the third argument:

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

3 Comments

Thanks, but in this case, changing of style will also invoke watcher.
when change of style, compare newValue[1].width and oldValue[1].width. If not equal,not do anything
hmm but that can't guarantee that others didn't change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.