user1361529
user1361529

Reputation: 2697

How to use angular directives that need parameters conditionally

I am looking for a solution that lets me use either ng-repeat or collection-repeat for a repeating list depending on a set variable.

I understand there are the following possibilities:

  1. Use dynamic templates and load the right template at run time
  2. Potentially use ng-attr

I want to avoid 1, because I don't want two templates - I'll have to keep updating code in both.

As far as 2 is concerned, it does not look like I can apply it to directives that pass parameters (Angular - Use attribute directive conditionally)

What I want to achieve is this:

//if $root.platformOS == "desktop"
<ion-item ng-repeat="event in events| filter:search.text" item-height="event.Event.height" id="item-{{$index}}">

//if $root.platformOS != "desktop"
<ion-item collection-repeat="event in events| filter:search.text" item-height="event.Event.height" id="item-{{$index}}">

Thank you.

Upvotes: 0

Views: 138

Answers (1)

Estus Flask
Estus Flask

Reputation: 222498

app.directive('repeat', function ($compile, $rootScope) { 
  return {
    restrict: 'A',
    priority: 2000,
    terminal: true,
    link: function (scope, element) {
      var repeatDirective = ($rootScope.platformOS == 'desktop') ? 'ng-repeat' : 'collection-repeat';

      element.attr(repeatDirective, element.attr('repeat'));
      element.removeAttr('repeat');
      $compile(element)(scope);
    }
  };
});

This way the directives are abstracted to a single one, since their syntax is the same.

Wrapping both repeats into a directive that are switched in directive's template would be the best, but it may be undesirable if extra wrapper elements don't suit the layout.

Upvotes: 1

Related Questions