Question

In several places, I'm creating a table which has two or more variants. It shows the main data and some details columns. The main data are always the same and the details vary according to user's selection. Let's say, it looks like either

Name Count LongDescription Price

or

Name Count Availability    Price

or

Name Count Weigth Volume   Price

It boils down to tons of

  • ng-if="detail=='description'"
  • ng-if="detail=='availability'"
  • ng-if="detail=='description' || "detail=='availability'"

First I shortened the nice descriptive names to a single letter in order to remove the clutter. Then I thought to employ some convention and create my own directive called detail:

detail="d"     => ng-if="detail=='d'"
detail="da"    => ng-if="detail=='d' || detail=='a'"

or maybe

detail="da"    => ng-if="'da'.contains(detail)"

I got it (sort of) working by copying and adapting the source of ngIfDirective, but creating a directive translating to ng-if feels cleaner. So my questions:

  • What way is better?
  • How can I write the directive translating to a different one?
Était-ce utile?

La solution

Have your attribute restricted directive add a new ng-if attribute whose value is generated based on its own value, then recompile:

.directive('detail', function($compile){
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      if(!attrs.ngIf) { // prevent infinite loop
        switch (attrs.detail) {
          case 'd':
            attrs.$set('ngIf', "detail == 'd'");
            break;
          case 'a':
            attrs.$set('ngIf', "detail == 'a'");
            break;  
          case 'da':
            attrs.$set('ngIf', "detail == 'd' || detail =='a'");
            break;
        }
        $compile(elem)(scope); // relink directive element
      }
    }
  }
})

Usage:

<div detail="d">My element exists because: <b>$scope.detail == 'd'</b></div>

Plunker Example

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top