Thursday, 21 March 2013

AngularJS directives : template attribute

Introduction

As explained in the introduction item, we like to create a directive that shows a group of elements underneath a header with a title.
Directives are sometimes described as a templating option. And looking at the directives item in the developer guide, we see that we can define a template with a directive.  So lets try that first to see if we can create our panel requirements.

template attribute

So this is the code we put in our html page.
<div my-dir1 title="{{panelTitle}}" >Contents of the panel</div>

Where the panelTitle is defined as a model value in the controller. The my-dir1 is the attribute that we have defined as a custom directive in AngularJS.  The simplified version, without the css stuff, could look like this.
demo.directive('myDir1', function version1() {
        return {
            restrict: 'EA'
            , scope: {title: '@title'}
            , template: '<div >Panel title {{title}}</div>'
        };
    });

The scope attribute defines that we define a model value ‘title’ in the child scope created for the directive and that it is linked with the attribute title on the element.

And with template, we define the text that must be used in the HTML page. It contains a reference to the newly created title model value in the child scope.

If we run the page, we see that we don’t have the expected result.

directives_post2_fig1

The good thing is that we can change the panel title by changing the value in the input element.

replace attribute


As we can see in the above image, the contents of the div element, in our case the text ‘Contents of the panel’ is removed. Looking back in the developers guide, we see also that there exists a replace attribute.

So maybe we should put the value at ‘false’ so that there is no replacement of the div contents. But again, it is not the desired effect. It looks even that the replace attribute had no effect.  But if we look better at the HTML structure we see the difference.

With replace false, only the contents of the element is replaced. When we use the value true, the entire element is replaced by our template but the attributes, like class, of the original element are appended to the template element.

Conclusion


Using the template attribute of the directives object, we are not able to handle a situation where we need to preserve or use the content of the element where we place the directive on. Well not in the form we have used it now. In the next blog item I’ll show you the solution for these cases.

The above described example shows us how we can use the directive feature of AngularJS where we like to enrich the element on which we have placed the directive. Enrichment like behaviour or look and feel with CSS.

No comments:

Post a Comment