Angular--$compile compiling service and instructions

Source: Internet
Author: User

$compile

This is a build service. Compile a template of an HTML string or DOM to create a function that joins the scope with the template.

The compiler service mainly compiles DOM elements for instructions, and the following large section is the main instruction.

The following is an example of a declared directive with an instruction definition object:

  var mymodule =Angular.module (...); Mymodule.directive (' Directivename ', ["injectables",...,functionFactory (injectables,...) {var directivedefinitionobject ={priority:0, Template: ' <div></div> ',//or//function (TElement, tattrs) {...},//Or//Templateurl: ' directive.html ',////function (TElement, tattrs) {...}, replace:False, transclude:False, restrict: ' A ', Scope:False, Controller:function($scope, $element, $attrs, $transclude, Otherinjectables) {...}, Controlleras: ' Stringalias ', require: ' Siblingdirectivename ',//or//[' ^parentdirectivename ', '? Optionaldirectivename ', '? ^optionalparent '],CompilefunctionCompile (telement, Tattrs, transclude) {Return{pre:functionPreLink (Scope, ielement, Iattrs, controller) {...}, post:functionPostlink (Scope, ielement, Iattrs, controller) {...} }//Or//return function Postlink (...) { ... }}, // or // Link: { // pre:function prelink (scope, ielement, Iattrs, Controller) {   ...}, // post:function Postlink (scope, ielement, Iattrs, controller) {...} // } // or // link:function postlink (...) { ... }   }; return Directivedefinitionobject;});             

This is a complete instruction, the properties of the returned object are written on the above, the following for the instruction object properties of the introduction, not one by one write the sample code, the main write down after the simple OK.

Note: Any parameters that are specified are set to the default values. The default values are listed below.

Directive Definition Object

The object defined by the directive provides a description for the compiler, whose properties are:

Priority
When there are multiple directives defined in a DOM element, it is sometimes necessary to specify the order in which the directives are applied. Before a compilation function is called, it is sorted by priority. The greater the value of this property, the higher the priority, and the more it will be compiled. The order of directives with the same precedence is undefined. The default priority is 0. Terminal

If this property is set to true, then the priority of the current instruction will be placed in the last set that will be executed (any instruction at the current priority will still be executed as a setting with undefined precedence)

Scope

If set to true, the directive creates a new (scope) scope. If you define a new scope on more than one instruction in a DOM, you can create only one new scope. After a template has a new scope, the rules for that scope do not apply to the root node where the template resides.

If set to {}, a new, isolated scope is created. The scope does not inherit its parent scope, so that the creation of reusable directives is not the data that affects the parent scope.

This isolated scope has an object that consists of a set of data from the parent scope that is prefixed by the following object name:

@or @attr: A property value on a DOM element that combines a local scope property. The string type is bound on the DOM element and in the instruction scope. If no name is specified, it is the same as the name in the assumed instruction scope.

=or =attr: Sets the two-way binding of data between the instruction scope and the parent scope. If no name is specified, it is the same as the name in the assumed instruction scope.

&or &attr: Provides an expression that executes in the context of the parent scope.

Controller

The Controller constructor for the directive. The controller will be instantiated before precompilation and can be shared with other instructions (see the Require property). This enables communication between instructions and enhances the behavior of each other. The following parameters can be written:

$scope: The current scope associated with the element.

$element: the current element.

$attr: The property on the current element.

$transclude: A linking function that is pre-bound to the correct embedding range. The range can be overridden by one of the first optional parameters. function ([scope], CLONELINKINGFN).

Require

Another instruction is required and its controller is injected as a fourth parameter into the linking function. The string name (or string array) of the instruction needs to be injected. If an array is used, the injected parameters will be in the corresponding order in an array. If no such instruction is found, or if the directive does not have a controller, an error will occur. The property name prefix is:

No prefix: The controller required to locate the current element. If no errors are found, an error is thrown.

? : Attempt to locate the desired controller, if not found, pass an empty function.

^: Search for the desired controller by searching the parent of the element, and throw an error if not found.

^: Search for the desired controller by searching the parent of the element, or pass an empty function if not found.

Controlleras

The alias of the controller within the scope of the instruction. The alias of the controller to be referenced in the directive template. This directive requires that this configuration be defined within the scope of application. Useful when an instruction is used as a component.

Restrict

A subset of the EACM, which restricts the instruction to a specific directive declaration.

E: element name,<my-directive></my-directive>

A: Element properties, <div my-directive= "Exp" ></div>

C: Element class: <div class= "MY-DIRECTIVE:EXP;" ></div>

M: note,<!--directive:my-directive exp--and

Template

Replaces the instruction block of the content of the HTML with the current element. The procedure updates all the properties/classes of the previous old element on the new element. This property can specify a template as a string or a function template, takes two parameters telement and Tattrs, and returns a String value that represents the template.

Templateurl

is basically the same as the template, but is loaded by the specified URL. Because templates are loaded asynchronously, both Conplie and link are agreed to wait for the template to load out.

Replace

Specifies the location where you want to insert the module, false by default.

True: The template will replace the current element.

False: The template will replace the contents of the current element.

Transclude

Compiles the contents of the element and makes it valid within the directive. This causes the component to have a private state, and the embedded part is included in the parent scope.

True: the directive can embed content.

False: Embedding the entire cell includes any directives defined at a lower priority level.

Compile

function compile (telement, tattrs,transclude) {...}

The compile function assigns the transformation of the template. Because most directives do not do template conversions, it is not used frequently. Examples of compile that need to be used to convert templates are ngrepeat, or asynchronous loading of content, such as Ngview. The following parameters are required for compilation:

TElement: The element that the template element, which is declared by the directive. It is only safe to make template conversions on elements and child elements.

Tattr: The properties of the template properties that are shared among all instructions compile functions.

Transclude: A transclude linking Function-functions (scope, CLONELINKINGFN)

Note: If templates are cloned, then the template instance and the link instance are different objects. Therefore, all DOM nodes that are cloned in the compile function are unsafe for DOM conversions. Specifically, Dom snooping should be in the link function instead of within the compile function.

Note: The compile function cannot manipulate instructions to recursively use its own template or compile function. Compiling these instructions will result in an infinite loop and stack overflow error. You can use the Postlink function manually to force a template for compiling directives instead of relying on manual compilation through template or Templateurl or in the Compile function templates.

Link

This property is used if the Compile property is not defined.

function link (scope, ielement, Iattrs,controller, Transcludefn) {...}

The link function registers the DOM listener and updates DOM operations, which are executed after the template is cloned. Most of the instruction logic is placed in this area.

Function parameters:

Scope: The scope of the instruction used by the registered listener.

IElement: An element instance that uses the element of the directive. When a child element is already associated, it is safe to operate within the Postlink function only.

Iattrs: An attribute instance, a property declared on this element, shared within the linking function of all instructions.

Controller: If the element that has at least one instruction defines a controller, then it is a director instance. The controller is shared across all instructions, which allows the command to use the controller as a communication channel.

Transcludefn: A linking function that is pre-bound to the correct embedding range. The range can be overridden by an optional first parameter--function ([SCOPE],CLONELINKINGFN)

pre-linking function: Executes before associating a child element.

post-linking function: Executes after the child element is associated.

$compile usage:

$compile (element,transclude,maxpriority);

element: The elements or HTML strings that will be compiled and inserted into the template.

Transclude: A valid function within a directive. Function (angular. scope,cloneattachfn=)

Maxpriority: Applies only if the instruction is lower than the given priority. Affects only the root element and does not affect child elements.

Return:

A connection function that binds an HTML template to a scope.

Scope: The scope of the binding.

Cloneattachfn=: If cloneattachfn= is provided, the connection function will clone the template and call the CLONEATTACHFN function to allow the cloned element to be attached to the appropriate place in the DOM document.

Cloneattachfn are called as:

CLONEATTACHFN (Clonedelement,scope);

Clonedelement: A cloned primitive element that is passed to the compiler.

Scope: Where the current scope and linking functions perform.

Call the linking function to return the elements of the template. There is another primitive element that will be passed, or the cloned element is provided with CLONEATTACHFN.

The $digest () is not updated until after the connection view is called, which is done automatically by angular.

If you need to get a bound page, there are two ways to do it:

1. If you do not want to request a clone template and create a DOM element before passing it to the compiler and keeping this reference range: var element = $compile (' <p>{{value}}</p> ') (scope);

2. On the other hand, you need the element to be cloned, and the view reference from the original example will not point to the clone, but will be the template to be cloned. In this case, you can access the clone through CLONEATTACHFN:

  var templateelement = angular.element (' <p>{{value}}</p> ');  Scope = ...; // define scope  var clonedelement = $compile (templateelement) (scope,function//  Add a clone element to the appropriate seat in the HTML document})     

Using code:

  <div ng-app= "Demo" Span style= "color: #0000ff;" >> <div = "Testctrl as CTRL" > <div id= " Contianer ">a</ Div> </div> </div>  
(function() {Angular.module ("Demo", []). Service ("Compiletest", ["$compile", Compiletest]). Controller ("Testctrl", ["$scope", "Compiletest",testctrl]) function Compiletest ($compile) {this.add = function (s) { var element = angular.element (' <span>{{ctrl.words}}</span> ' ); Angular.element ("#contianer" function Testctrl ($scope, compiletest) {var vm = thisvar e = angular.element ("#contianer" ; Compiletest.add ($scope); }; }()); 

$compile. directive.attributes

An object that contains the canonical DOM element attributes and can be shared between the compile of the instruction and the link function. This value reflects the current binding's state {{}}.

Method :

$addClass (Classval);

Classval the added CSS class for the specified element. If an animation style is executable, the animation style is triggered.

$removeClass (Classval);

CLASSVAL Specifies the CSS class that the element is removed from. If an animation style is executable, the animation style is triggered.

$updateClass (newclasses,oldclasses);

Updates the CSS class for the specified element. Newclasses is the new CSS class that will replace the oldclasses (existing style).

$observe (KEY,FN);

Observe a property that is inserted internally. The next time $digest only, this observation function will be executed once. This function is called once when the value of the inner insert has changed.

$set (Name,value);

Sets the DOM element property value. Name: Property name, Value: property values.

Property:

$attr;

Element properties.

Using code:

  . red{      color:red  }  . blue{      color:Blue}    
  <DivNg-app= "Demo"><div ng-controller = "Testctrl as CTRL" > <div class= "Blue TestClass"  Data-value= "value"  New-dir>11111</ div> </div> </div< Span style= "color: #0000ff;" >>                 
(function() {Angular.module ("Demo", []). Directive ("Newdir", Newdir). Controller ("Testctrl", Angular.noop)function Newdir () {return{ Restrict: "Acem" function  (Scope,element,attrs) {attrs. $addClass ("Red" ); Element.bind ("MouseOver", function); }); var count = 0function () {Console.log (Count++ 

For the instruction this piece, really need to write many more uses in order to really understand these content and the usage ... This summary article about the instruction does not have much direct use of the code, but each of the properties have been tested for usage, also wrote some of their own projects or write their own play plug-ins ... Well, write this for the time being, then go on to learn another service ...

Angular--$compile compiling service and instructions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.