Angular direve ve Summary

Source: Internet
Author: User
Tags list of attributes

Angular direve ve Summary
What is directive)

Custom HTML elements and attributes can be simply understood as a function running on a specific DOM element. commands can extend the functions of this element.

Simple Example of commands
angular.module('myApp', []).directive('myDirective', function() {    return {        restrict: 'E',        replace: true,        template: 'Click me to go to Google'    };});

Four Methods


  
  Transmit data to commands

Set the corresponding attribute in the command

template: '{{ myLinkText }}'

Specify the attribute value in the element.

Problems arising from shared scopes 

If the Controller is removed or in the Controller's scope
When we define a property called myUrl, we are forced to modify the code, which is very costly and frustrating.

scope: {    someProperty: "needs to be set"}

An isolation scope is created. attributes in this scope can only be used in the method or template string of the instruction.

Bind to the parent scope and pass values through attributes
Scope: {someProperty: '@'} // Attribute Value
 

Different names

Scope: {someProperty: '@ someAttr'} // some-attr instead of som-property
Built-in commands

Ng-start

The name of the directive Parameter name (string) command, used to reference a specific command in the view. The factory_function (function) function returns an object that defines all the actions of a command. $ Compile uses the object returned by this method to construct the command behavior when DOM calls the command. You can also directly return a function, which is usually called the postLink function. We can use it to define the link function of the command. The parsing process of directive when AngularJS starts an application, it regards the first parameter as a string and registers the object returned by the second parameter in the name of this string. The AngularJS compiler will parse the places where the main html dom elements, attributes, comments, and CSS class names use this name, and reference the corresponding commands in these places. When it finds a known instruction, it inserts the DOM element corresponding to the instruction in the page. The factory function of the instruction is called only once when the compiler matches the instruction for the first time. Similar to the controller function, we use $ injetor. invoke to call the factory function of the command. When AngularJS encounters a named command in the dom, it will match the already registered command and search for it in the registered object by name, the lifecycle of an instruction starts at $ compile and
End with all settings of link Method directive
Angular. module ('myapp', []). directive ('myctive', function () {return {restrict: String, priority: Number, terminal: Boolean, template: String or Template Function: function (tElement, tAttrs) (...}, templateUrl: String, replace: Boolean or String, scope: Boolean or Object, transclude: Boolean, controller: String or function (scope, element, attrs, transclude, otherInjectables) {...}, controllerAs: String, require: String, link: function (scope, iElement, iAttrs ){...}, compile: // returns an object or connection function, as shown below: function (tElement, tAttrs, transclude) {return {pre: function (scope, iElement, iAttrs, controller) {...}, post: function (scope, iElement, iAttrs, controller ){...}} // or return function postLink (...) {...}}};});
Restrict (string)

Restrict is an optional parameter. It tells AngularJS how the command can be declared in the DOM. Mo
Recognizes AngularJS that the restrict value is A, that is, it is declared as an attribute.
E (element)


  

A (attribute, default value)

  

C (class name)

 

M (comment)

<--directive:my-directive expression-->

These options can be used independently or together.

Angular. module ('myctive', function () {return {restrict: 'ea '// input element or attribute };}); // call method <-- as an attribute -->
  <-- Or as an element --> Element selection element: complete function, not an extension of some elements

  
Attribute: add data or behavior to an existing element
 
  

Extension of my-clock
-Standard: whether the defined instruction contains the core behavior of a component, or modifies or extends a core component with additional behavior, status, or other content (such as analog clock ).
-Another important criterion is to determine whether a command is created, inherited, or isolated from its environment.

Priority (numeric)

Optional. The default value is 0. The higher the value, the higher the priority.
If there are two commands with the same priority on an element, it is declared that the preceding commands are called preferentially.
NgRepeat has the highest priority among all built-in commands, 1000

Terminal (Boolean)

Terminal is a Boolean parameter and can be set to true or false.

Function

This parameter is used to tell AngularJS to stop running commands with a lower priority than the current command. But it is the same as the current command
Commands with the same priority will still be executed.

Example

Examples of using the terminal parameter are ngView and ngIf. NgIf has a higher priority than ngView.
If the value of the formula is true, ngView can be executed normally. However, if the value of the ngIf expression is false, ngView will not be executed because of its low priority.

Template (string or function)

Optional. Two formats:
-A piece of HTML text;
-A function that can take two parameters. The parameters are tElement and tAttrs, and a character representing the template is returned.
String

What are the parameters tElement and tAttrs?

TElement: the element of the template
TAttrs: attributes of the template's element

Template requirements: AngularJS processes template strings like HTML. The template can be marked with braces to access the scope,
For example, {expression }}. If the template string contains multiple DOM elements or is composed of only one individual text node, it must be wrapped
Contains a parent element. In other words, a root DOM element must exist:
template: '\
<-- single root element -->\ Click me\ When using two elements, wrap them in a parent element \ \In addition, pay attention to the backslash at the end of each line so that AngularJS can correctly parse strings of multiple lines. In actual production, it is better to use the templateUrl parameter to reference an external template, Because reading and maintaining multiple lines of text is a nightmare. TemplateUrl (string or function)

Optional.
-A string that represents the path of an external HTML file;
-A function that accepts two parameters: tElement and tAttrs, and returns an external HTML file
Path string.

URL of the template will be implemented through the security layer built in AngularJS, especially $ getTrustedResourceUrl, which can protect the template from being loaded by untrusted sources. When calling the command, Ajax will be used in the background to request the HTML template file for local development, you need to run a local server in the background to load the HTML template from the file system. Otherwise
Cross Origin Request Script (CORS) errors. -Therefore, the xampp template loading must be enabled asynchronously, meaning that the compilation and link should be paused, waiting for the template to be loaded. Loading a large number of templates asynchronously through Ajax will seriously slow down the speed of a client application. You can cache HTML templates before deployment (Chapter 1) replace (Boolean)

Optional. boolean. The default value is false.
False: The template is inserted into the element that calls some commands as a child element.

  
.directive('someDirective', function() { return { template: ' 
some stuff here 
' }; }); 

After the call:

 
some stuff here  

True: Same level element.

 
some stuff hereScope command scope 

Optional. The default value is false.
False: if the parent scope is used, the modification to the attribute in the instruction will directly apply to the parent scope.
True: inherits from the parent scope and creates a new scope object. The parent scope can be accessed in the instruction. The modification does not affect the parent scope.
{}: Create an isolation scope. You cannot access the parent scope. The modification does not affect the parent scope.

Binding policy of the isolation scope @: local scope attribute. Use the @ symbol to bind the value of the local scope with the DOM attribute. The internal scope of the instruction is acceptable.
Variables in the external scope =: bidirectional binding: You can use = to bind the attributes in the local scope to those in the parent scope.
Just like data binding, local attributes reflect changes in the parent data model. & Bind with the parent Method

  
Scope: {ngModel: '=', // bind the ngModel with the specified object to onSend: '&', // pass the reference to this method fromName: '@' // store the string associated with fromName}Transclude embedding

Optional parameter. The default value is false, which determines whether the html code under the element is embedded in the template.

Transclude: true is used only when you want to create an instruction that contains any content.

Example:
 
  • First link
  • Second link
angular.module('myApp', []) .directive('sidebox', function() { return { restrict: 'EA', scope: { title: '@' }, transclude: true, template: '\ \ {{ title }} \ \ \ \ ' }; });

The embedded position is the ng-transclude tag,
-Disadvantages:
If the command uses the transclude parameter, the number of normal listeners will not be available in the Controller (as described below ).
The data model has changed. This is why the $ watch service is always recommended in linked functions in best practices.

Controller (string or function)

The controller parameter can be a string or a function.

Angular. module ('myapp', []). directive ('myctive', function () {restrict: 'A', // always need controller: 'somecontroller'}) // other places in the application, which can be angular of another file contained in the same file or index.html. module ('myapp '). controller ('somecontroller', function ($ scope, $ element, $ attrs, $ transclude) {// The controller logic is placed here });

An inline controller can be defined in the instruction via anonymous constructor.

Angular. module ('myapp', []). directive ('myctive', function () {restrict: 'A', controller: function ($ scope, $ element, $ attrs, $ transclude) {// here is the Controller logic }});

Parameter description:
- The current scope associated with the directive element .? The element corresponding to the current command.
-$ Attrs is an object composed of attributes of the current element. For example, the following elements:

 
 

$ Attrs receives the following values:

{id: "aDiv",class: "box"}
$ Transclude
You can embed a link function. The link function is pre-bound to the corresponding embedded scope.
Purpose:
The function used to clone elements and operate DOM. Operating DOM in the controller is contrary to the AngularJS style, but you can use the link function.
This requirement is met. It is recommended to use transcludeFn only in the compile parameter.
Add a hyperlink to an instance:
    angular.module('myApp')    .directive('link', function() {        return {            restrict: 'EA',            transclude: true,            controller: function($scope, $element, $transclude, $log) {                $transclude(function(clone) {                    var a = angular.element('');                    a.attr('href', clone.text());                    a.text(clone.text());                    $log.info("Created new a tag in link directive");                    $element.append(a);                });            }        };    });

What is the clone parameter?

Differences with link:
Command controllers and link functions can be exchanged. The Controller is mainly used to provide reusable behavior between commands, but the linked function can only define behavior in the current internal commands, and cannot reuse between commands.
The link function can isolate commands from each other, while the controller defines reusable behaviors.
If you want to expose the API of the current command to other commands, you can use the controller parameter. Otherwise, you can
Use link to construct the functionality of the current command element.
If we use scope. $ watch () or want to interact with DOM elements in real time, using the link is a better choice.

ControllerAs (string)

The controllerAs parameter is used to set the alias of the controller. You can publish the Controller in this name.
Purpose:
Powerful anonymous controller creation in routing and commands
Capability. This capability can create a dynamic object as a controller, and this object is isolated and easy to test.

Require (string or array)

Controllers that load other commands
As the fourth parameter of the current command link function
Modifier:
-? : If the required controller is not found in the current command, null is used as the fourth parameter passed to the link function.
-^: If the ^ prefix is added, the command searches for the Controller specified by the require parameter in the upstream command chain.
-? ^: Combine the actions of the preceding two options. We can selectively load the required commands and search for them in the parent command chain.
-No Prefix: If there is no prefix, the command will be searched in the Controller provided by itself. If no controller (or command with the specified name) is found, an error will be thrown.

The compilation process of angularjs lifecycle compilation phase
In the compilation phase, AngularJS traverses the entire HTML document and processes the instructions declared on the page according to the instructions in JavaScript.
Once commands and sub-templates are traversed or compiled, the compiled template returns a letter called a template function.
Number.
We have the opportunity to modify the compiled DOM tree before the instruction template function is returned.
At this time point, the DOM tree has not been bound to data, which means that there will be very few operations on the DOM tree at this time.
Performance overhead.
Based on this, built-in commands such as ng-repeat and ng-transclude will be executed at this time, that is
Bind data in any scope to operate the DOM.

For example, ng-repeat traverses the specified array or object and constructs the corresponding DOM structure before data binding.

Once a command is compiled, it can be accessed through the compilation function immediately. The signature of the compilation function contains the element where the access command declaration is located (tElemente) and other attributes of the element (tAttrs). This compilation letter
Return the preceding template function, which contains the complete parsing tree.

Since each instruction can have its own template and compilation function, each template also returns its own
. The commands at the top of the chain combine the template of the internal sub-commands into a template function and return the results. However, within the tree, you can only access the branch of the sub-commands through the template function.

Finally, the template function is passed to the linked function specified in each instruction definition rule in the compiled DOM tree.

Compile (object or function) is used to perform DOM operations before commands and real-time data are put into the DOM. It is safe to perform DOM operations such as adding and deleting nodes in this function. The compile and link options are mutually exclusive. If both options are set, the functions returned by compile are treated as link functions, while the link options are ignored. Compile the function to convert the template DOM. The linked function is responsible for linking the scope and DOM. Link stage

Use the link function to create instructions that can operate the DOM.
Role: responsible for setting event listeners, monitoring data changes and real-time DOM operations.
Parameters:

// Require 'somecontroller', link: function (scope, element, attrs, SomeController) {// operate DOM here to access the Controller specified by required}
The scope command is used to register the listener's scope within it. The iElement parameter represents an instance element, which is an element that uses this command. In the postLink function, we should only operate on this
The child element of the element, because the child element has been linked. The iAttrs parameter represents an instance attribute. It is a standardized list of attributes defined on an element and can be shared among linked functions of all commands. It is passed as a JavaScript Object. The controller Parameter points to the controller defined by the require option. If the require option is not set
The controller parameter value is undefined. In actual use cases, an click event is bound to an element. After a click event is clicked, the cookie is obtained and events such as keydown and keyup on the log information listening element are submitted, handle

Related Article

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.