Friday, May 16, 2014

Dynamic Template for AngularJS

How can you use a context-dependent template?

Use ngInclude

<ng-include src="'mytemplate.html'"/>
Here the src for ngInclude is an expression. Here I use a static template file so it is a string quoted with single quote here. You can set use an expression instead of static string. The expression can be set up in parent scope/context, so the  template is dynamic.
<ng-include src="getMyTemplate(param)"/>

Use $compile in link function of directive

You can use this if you template is really dynamic and composed from various sources. You use the link function in a directive to manipulate the html.
instApp.directive("fxRelationEditor", function($compile, $templateCache){
    return {

      link: function($scope, $element, $attrs, $templateCache){
            var topelement=angular.element($templateCache.get("template/report/relation_editor_top.html"));
            if ($scope.relationui.showselected){
            var editorhtml=flexdms.query.originalrelationeditor;
            //no report, default ui.
            if (!${


In the example above, we create a DOM element dynamically from various sources and set it as new template.

No comments:

Post a Comment