📜 ⬆️ ⬇️

Angular Light. We manage declarative data binding in HTML

In angular there are 2 tools for displaying information in the DOM - these are directives and declarative binding of data in HTML {{model}}.
While directives have great potential, declarative binding is a bit limited, it makes $ watch for a model with the ability to call filters and, by and large, that's all. And I would like more flexibility.

For example, if you look at the bindonce library for Angular.js, the main idea is a one-time output without using $ watch.
And in order to use it anywhere, for any attribute, the developer made a number of separate directives: bo-text, bo-href-i, bo-href, bo-src-i, bo-src, bo- class, bo-alt, bo-title, bo-id, bo-style, bo-value, bo-attr and bo-attr-foo . But in fact, they all do the same thing and, logically, it should be one directive.
It also deviates from the declarative data binding, conceived in Angular.js, i.e. instead
<a href="{{link}}">{{name}}</a> 
need to write
 <a bo-href-i="{{link}}" bo-text="name"></a> 
Those. for which declarative data binding was invented, in this situation does not work.

Therefore, the idea to implement directives for declarative data binding has emerged.
How it works in Angular Light - you just need to specify the name of the directive and put a “#” sign before it, i.e. instead of {{model}} will be {{#directive model}} .
Useless, but simple counter example:
 <div al-app> counter {{#counter model}} </div> 
We make a “model” binding and connect the “counter” directive, for simplicity I omitted the use of “model” in this directive:
 alight.text.counter = function(callback, expression, scope, env) { var n = 0; setInterval(function(){ n++; callback(n) // set result scope.$scan() // $digest }, 1000); } 
At the entrance to the directive, we get:
An example of how this works.
')
Next, an example with inserting a bindig into attributes, a loadLoginById directive that “simulates” data loading from a server:
 <div al-app al-init="user_id = '555'"> id = <input type="text" al-value="user_id" /> <br/> into href = <a href="http://example.com/?search={{#loadLoginById user_id}}">user's page</a> <br/> into title = <span title="{{#loadLoginById user_id}}">user</a> <br/> into text = {{#loadLoginById user_id}} </div> 
Example

And finally, the example with bindonce , one directive that replaces 11 of the bind-once library:
 <div al-app al-init="link = 'google.com'"> id = <input type="text" al-value="link" /> <br/> usual, with $watch = <a href="http://{{link}}">{{link}}</a> <br/> bindonce = <a href="http://{{#bindonce link}}">{{#bindonce link}}</a> <br/> aliase of bindonce = <a href="http://{{=link}}">{{=link}}</a> <br/> </div> 
Example

If declarative binding is coined for convenient output of information, why not use it in full?

Source: https://habr.com/ru/post/209108/


All Articles