To increase the flexibility of using directives, I added a “preprocessor” for directives. It is called at the time of the "connection" directive in the DOM. You can expand it or replace it with your own, which gives opportunities such as:
- Adding custom attributes to directives (like template, templateUrl, scope ...)
- Transformation of directives and their substitution
- Changing the location of directives, for example, to store part of directives in scope (well, what if you want to)
Next, a couple of examples:
Add the attribute "bold" to the directivealight.directivePreprocessor.ext - an array of "handlers" that are called from the preprocessor, insert your handler, check the
directive.bold attribute in it and change the contents of the element.
alight.directivePreprocessor.ext.splice(1, 0, { code: 'bold', // not necessary fn: function() { if(this.directive.bold) this.element.innerHTML = '<b>' + this.element.innerHTML + '</b>' } })
Example directive:
alight.directives.al.example = { bold: true }
Plunker example“Lazy” directive connectionTask: all directives with the “dyn” prefix are automatically loaded from the server at the time of their use from the corresponding file.
An example of a
dyn-directive directive and its connections:
<span dyn-directive="name"></span>
The directive file will be loaded by directive name:
dyn.directive.js alight.directives.dyn.directive = { template: '<b>{{title}}</b>', scope: true, link: function(element, name, scope) { scope.$watch(name, function(value) { scope.title = '+' + value + '+' }, { init:true }) } } // "" waitDirectives.directive.resolve()
Plunker exampleReplacing the preprocessor is in the
system.js file, see example.
')
Usually such opportunities are not needed in projects, but sometimes they are useful.
Previous articles:
Angular Light. We manage declarative data binding in HTML ,
Inheritance of directives in Angular Light