Mastering ngTemplate
ngBackbone advantages from NgTemplate - a light-weight DOM-based template engine, inspired by AngularJS. When we bind data (models/collections) to a component, any change on them triggers the template to re-synchronize. NgTemplate does it gracefully. It looks up the compiled template for the directives, evaluate the expressions and updates the directives only when expression has a changed state. For example in the component below we use data-ng-text directive to render world.name
actual value into i
element text node:
If the value changes this.models.get( "world" ).set( "name", "New world" )
the content of i
element responds.
Template expressions
Template expressions are a JavaScript code that NgTempplate
evaluates in the data scope (models/collections). So we can simply address a variable <i data-ng-text="world.name"></i>
or run an expression <i data-ng-if="world.counter > 10"></i>
Expressions evaluate in the context of the target element, so we can access the element with this
:
NOTE: In order to gain better performance keep to primitive expressions especially in cyclic directives e.g.
data-ng-text="foo.bar.baz"
,data-ng-text="!foo.bar.baz"
,data-ng-text="'string here'"
,data-ng-if="foo.bar > baz.quiz"
,data-ng-text="foo + 10
,data-ng-if="true"
,data-ng-prop="'disabled', true || false"
,data-ng-data="foo || bar, baz"
. Such expressions are being evaluated without use ofeval()
and therefore the process takes much less time and resources. You can check how the parser treats your expressions by studying content oftemplate.report().tokens
array
Directives
We use HTML-compliant data-ng-*
custom attributes to tell the template how exactly we want to bind the scope data to the element
NOTE:
data-ng-class
,data-ng-prop
,data-ng-attr
,data-ng-data
can be applied multiple times on an element likedata-ng-class-0
,data-ng-class-9
NgText
We use NgText
to modify element's textNode
NgProp
We use NgProp
to modify element's properties
NgAttr
We use NgAttr
to modify element's attributes
NgData
We use NgData
to modify element's dataset
NgClass
We use NgClass
to modify element's classList
NgIf
We use NgFor
to toggle visibility of an element (subtree) within the DOM
NgFor
We use NgFor
when we need to generate a list of elements (subtrees)
NgSwitch
We use NgSwitch
when we need to display on element (subtree) of a set of available options.
NgEl
We use NgEl
to modify element properties
NOTE: Using
NgEl
is rather discouraging as it cannot be cached and every model sync will cause the DOM modification even if the expression ofNgEl
wasn't changed
Last updated