Robert Kusznier
Robert Kusznier

Reputation: 6911

AngularJS directive: switch statement depending on attribute value

I have a directive which is given as an attribute one of 13 types it can take. Depending on the type the directive should return different HTML elements that represent the given type. The value of the type will be constant - won't change after directive is compiled.

<directive type="{{ type }}"></directive>

I have an architectural problem. Should I handle all the types inside 1 directive (so that the directive returns different templates depending on type value) or differentiate the type cases at the template level into 13 different directives (call a proper type of directive depending on type value)? In short should I put the switch (type) inside a inside a directive or leave it at the template level?

Then the implementation. What would be the implementation of the proposed solution? In short how to implement that switch (type) either inside a directive or a template.

Upvotes: 1

Views: 1296

Answers (1)

sdgluck
sdgluck

Reputation: 27257

It is probably easiest to go down the single-directive route, and in which case I can think of two solutions. The best depends on the size of the individual templates.

Small templates: ng-switch

Give your directive a single HTML file as it's templateUrl which contains an ng-switch with a ng-switch-when case for each type. It would look something like this:

// directive.js
angular.directive('directive', function() {
    return {
        scope: {type: '@'},
        templateUrl: '/path/to/directive/template.html'
    };
});

// template.html
<div ng-switch="type">
    <div ng-switch-when="somethingType">
        <!-- template for (type === "somethingType") -->
    </div>
    <div ng-switch-when="otherType">
        <!-- template for (type === "otherType") -->
    </div>
    <!-- ... -->
</div>

Large templates: ng-include

Use the same behaviour as in directive.js above but keep all your templates within their own individual HTML files local to the directive's directory and then use an ng-include to pull in the correct template according to the value of type.

/path/to/directive
 - /templates
    - somethingType.html
    - otherType.html
 - directive.js
 - template.html

// template.html
<div ng-include="'/path/to/directive/templates/' + type + '.html'"></div>

Upvotes: 2

Related Questions