AngularJS Simple Partial Include Directive. Use this code to help you reuse your partial templates inside other templates. You can have optional switching of views also if you wanted. Sorry no demo at the moment.
Separate out your HTML template which you want to reuse and include in other templates.
partial/common-view.html
1 2 3 4 5 |
<div class="common-template"> content of partial here... </div> |
Now create a new directive in your module. Using a directive here gives us flexibility of creating it as a component. For example, the functionality in the scope can be reused wherever we include our directive – so we don’t have duplicated controller code. Nice.
directives/commonView.js
1 2 3 4 5 6 7 8 9 10 |
angular.module("app").directive("commonView", function() { return { restrict: 'A', templateUrl: 'partials/common-view.html', scope: true, transclude : false }; }); |
Naming: Your directive named camel case will be available in your templates in lower case hyphen seperated.
Scope: Add scope:true if you don’t want this directives scope to be directly linked to other directives (use true if it doesn’t rely on other directives scopes).
Transclude: Add transclude:true if you want the HTML content in your directives HTML tag to go inside your partial template (where you will include ng-transclude and it will appear).
Then you can include it in your other templates like this:
template1.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<ul ng-switch-when="1" class="view1"> <li ng-repeat="result in data.results"> <div common-view></div> view2 stuff... </li> </ul> .... <ul ng-switch-when="2" class="view2"> <li ng-repeat="result in data.results"> <div common-view></div> view2 stuff... </li> </ul> |
Voila!.