jeudi 31 mars 2016

What's the best practice when an AngularJS directive has a lot of bindings in its isolated scope?

Suppose each card-item directive needs to know a lot of outside contexts and acts accordingly.

We could make a service to monitor the outside world, and inject the service into card-item directive, like:

scope: {
  item: '=',
  service: '=',
}

<card-item item="card" 
           service="ItemService">
</card-item>

This seems like a bad practice, because the directive knows too much about the service (e.g. calls the service's functions inside directive).

Many posts about AngularJS best practices suggest isolation, like following.

But it still doesn't feel right here:

scope: {
  item: '=',
  isSelected: '&',
  inSelectMode: '&',
  inMoldMode: '&',
  onToggleSelect: '&',
  onTogglePreview: '&',
  onToggleSort: '&',
  onDelete: '&',
  isPreviewing: '&',
  isSorting: '&',
  locales: '=',
  printUrl: '=',
}

<card-item item="card" 
           is-selected="ItemService.isSelected(card)"
           in-select-mode="ItemService.inSelectMode()"
           in-mold-mode="ItemService.inMoldMode()"
           on-toggle-select="ItemService.toggleSelect(card)"
           on-toggle-preview="ItemService.togglePreview(card)"
           on-toggle-sort="ItemService.toggleSortMode()"
           on-delete="ItemService.removeParticle(card)"
           is-previewing="card === entityInPreview"
           is-sorting="ItemService.inSortMode()"
           locales='LocaleService.currentLocales'
           print-url="getPrintUrl(card)">
</card-item>

What's your suggestion?

Thanks for reading.

Aucun commentaire:

Enregistrer un commentaire