Angular Customizable Templates

The code on GitHubAngular Customizable Template

I’m currently working on a project where we have inherited a lot of AngularJS code. The application was developed as a prototype, so some things were coded in a very quick and provisional way and with a lack of very good practices.

We are now working on the transformation of the prototype to a real product. I’ve ended up making a deep refactoring of all the browser-side code that in some parts it seems more a reboot than a refactoring.

One of the things that terribly frightened me more was to bump into code containing those huge chains of nested $parent.

<span ng-if="$parent.$parent.$">

It is generally a very bad idea to access to the parent scope using the $parent property, but it is even worse to reach that level of nesting. The code is unmaintainable. A minimum change in the template will change the depth of the accessed scope and will invalidate all the bindings. There are some core directives that create new scopes, for example the ng-if directive.

It seems that kind of code was driven by the need to customize the HTML templates of certain custom directives.

<my-directive customHeader="/templates/customHeader.html">
  <div>Some content wrapped by the directive using transclusion</div>

The <my-directive> directive is based in a HTML template and it is declared with an isolated scope. When the customHeader attribute is defined, the directive includes that template HTML file using the <ng-include> directive.

The problem is that all the code included in the customHeader.html file will be accessing the isolated scope of the <my-directive>. An isolated scope doesn’t use prototypal inheritance, so the customHeader.html template needs to use the $parent property to access to the scope where it is supposed to be defined.

While working on that kind of code I thought another way to make it possible to create directives based on HTML that allow the customization of some parts of their templates while retaining access to the right scope.

I made the Angular Customizable Template module. It is based on ‘element’ transclusion. It currently has the drawback that the mechanism only works for directives that wrap its content using simple transclusion. So it is still a work in progress but I think it can give you some ideas.
Sigue leyendo