How to build your own directive

Canvas for TM1 comes with 30 directives (tm1-ui-dbr, tm1-ui-subnm...) which will help you to build quickly a page. If you combine these Canvas directives with the AngularJS Directives such as ng-repeat and ng-if, you can already achieve a lot. By combining these existing directives, you can build more sophisticated components. When you start replicating the same component in different pages, this is where you need to start thinking about bulding your own directive.

What is a directive?

A directive can be anything, it could be just an HTML component or a part of it that you want to reuse in multiple pages.

Why building your own directive?

  • Avoid duplicating the same code on multiple pages.
  • Reduce the maintenance into one file.
  • Create a reusable component for all your future projects.
  • Build a component that you can share with the Canvas community.

Building a directive is very easy, just follow these steps and you will be able to build your first directive in 5 minutes.

Directive structure

A directive can just be a JS file or with an HTML file combined. In this example we are going to build a directive which is going to show all attributes of an element. For this directive we will need a view (an HTML file) and a controller (JS file) to where we will define our directive:

Create the HTML components

The HTML page used in the directives is very similar to an HTML page you use on your main page except that you do not need to specify a controller:

The link between the view (display-attributes.html) and the directive itself (display-attributes.js) will be defined in our JS file.

For our view, let us just start with a simple row from which we will then define the contents we want to show:

<div class="row">
    View contents
</div>

You can download the full example here:

Create the directive definition:

If this is your first directive, the structure will be slightly different at the beginning. The structure of the "controller" used in a directive is going to be slightly different than the one used for a main view:

You can download the code here:

The Canvas server is going to load all the files in the JS folder. So you just need to put your new directive (JS file) in the JS folder and you will be able to use your directive in your page.

How to use the directive in a new page

To use the directive, you just need to call the HTML tag with the name of your directive. If your directive is called myDirective, the HTML tag will be <my-directive></my-directive>, in our example, we use the following code to call our directive:

<display-attributes tm1-instance="dev" 
                    tm1-dimension="{{selections.dimensionModal}}" 
                    tm1-element="{{selections.elementModal}}"
                    tm1-alias="{{selections.aliasModal}}" 
                    panel-Class="{{selections.panelClass}}">
</display-attributes>