How do I watch elements of an AngularDart collecti

2019-02-14 06:21发布

问题:

I have a model:

class WordList {
  List<Word> words = [];
}

It's created via dependency injection into one of my views.

@NgController(
    selector: '[list-ctrl]',
    publishAs: 'ctrl'
)
class ListCtrl {
  WordList wordList;
  Scope scope;

  ListCtrl(this.router, this.wordList, this.scope) {
    scope.$watchCollection("", onChange );
  }

I'd like to run some logic whenever an item is modified from that list. How do I accomplish this?

I believe the key is in the $watchCollection, but I can't figure out what to pass as a watch expression. "ctrl.wordList.words" will tell me when items are added/removed, but not changed.

回答1:

$watchCollection as you point out can only watch for changes in the List not for changes in the items of the list. The reason for this is that watching each object would have explosive number of properties.

scope.$watch(() => wordList, onChange);

You could implement the onChange method in a way that it would create further watches on each new item as well as deregister the watch on item removal form the collection.