Study notes-angularjs (10)

Source: Internet
Author: User

I've been talking about custom directives, but there's never been a systematic understanding, and now we need to learn how to use custom directives to enrich HTML tags, attributes, and multi-functional tags (or attributes). Spicy, what is the instruction? To understand the instructions, you first need to understand the HTML compiler of ANGULARJS, simply let the browser know your custom instruction or angular instruction set, apply its behavior to the DOM (view), the two processes compile and link, the compile phase is to traverse the DOM and collect all the relevant instructions, Generates a link function that links the template to the scope, binds a scope, and generates a dynamic view by invoking the linked function called through the compile phase. Any changes to the scope model are reflected in the view, and any user actions on the view are reflected to the scope model.

In the final analysis, the behavior caused by the presence of a property, element name, CSS class name, or DOM changes allows you to extend the HTML representation in a declarative way, which is the instruction!

The official website also wrote a more detailed instruction demo (the specific attribute analysis is as follows):

varMyModule =angular.module (...); Mymodule.directive ('Directivename', function Factory (injectables) {//what does the injectables inside the factory function mean? Hope to know the people told    varDirectivedefinitionobject = {
Priority:0,//Priority Priority,dom There will be a lot of instructions, define the priority, you can make this command take precedence
Terminalfalse,//if set to true, the instruction will be executed at the end of the instruction set and in the same DOM.
Template'<div></div>',//or//function (telement, tattrs) {...},//templateurl: ' directive.html ',//or//function (telement, tattrs) {...},//template or Templateurl, as the name implies, templates file, can be written, can also be URL, can also be function (telement,tattrs) {return ...;}

Replacefalse,//whether to replace the current element

Transclude:false,//One of the important attributes,when used with Ng-transclude, when True, the contents of the original element (HTML, other instructions) can be extracted into the element with the directive Ngtransclude, the following examples are explained! (Note: the scope of external directives can be accessed internally by directives, and templates can also access external scope objects )

Restrict'A',//The format in which the instruction behavior is declared, with AECM, attribute <div my-directive= "exp" > </div>, Element *<my-directive></ my-directive>, Class*<div class= "MY-DIRECTIVE:EXP;" ></div>, notes <!--directive:my-directive Exp--and

Templatenamespace:'HTML',//template namespace, with ' HTML ', ' SVG ', and so on, default to ' HTML '

Scopefalse,//whether to create a new scope (for directives)
/*scope is one of the most difficult attributes to understand */

controller:function ($scope, $element, $attrs, $transclude, Otherinjectables) {...},//the controller constructs the object, the precompilation phase executes, $scope the current scope, $element the current element, $attrs the collection of attributes for the current element, and it is shared, and other directives can be obtained by its name (refer to dependency properties (introduced by the Require attribute). This makes it possible to communicate with each other in order to expand their capabilities. Of course it can be the controller name (then this controller needs to be declared in the application, so that it can be injected $attrs, $element manipulation instructions corresponding to the template DOM), $transclude, to manipulate the corresponding Dom of the embedding scope, That is, the DOM has been extracted into the elements of ngtransclude, here are examples!

Controlleras:'Stringalias',//Defining aliases for controllers

Require'Siblingdirectivename',//or//[' ^parentdirectivename ', '? Optionaldirectivename ', '? ^optionalparent '],//Requests that another controller be passed as a parameter to the current link function. This request requires the name of the controller that passed the requested instruction. Previous examples have been used in the form of custom validation, learning note-angularjs (eight)

Compile:function compile (telement, Tattrs, transclude) {//the element that contains the telement directive, the element attribute collection where the tattrs directive resides return{pre:function prelink (scope, ielement, Iattrs, controller) {...}, pos T:function Postlink (Scope, ielement, Iattrs, controller) {...} } //or//return function Postlink (...) { ... } //The compile function is used to handle situations where the template DOM needs to be modified (performed before DOM operations are placed in the DOM). Because most instructions do not need to modify the template, this function is not commonly used. Returns a function or an object that is equivalent to a link function when returning a function }, //or//Link: {//the link function is responsible for registering DOM events and updating the DOM. It is executed after the template has been cloned. It is also where most of the instruction logic code is written. Scope current scope, ielement the current element, iattrs the current element of the attribute collection, controller is the value of the above require property, so you can call require incoming Controller's property method, (including the previous Ngmodel or other Controller method with controller name defined by instruction Controller and Controlleras)//pre:function prelink (scope, ielement, Iattrs, controller) {...},//post:function Postlink (scope, ielement, Iattrs, controller) {...}// } //or//link:function postlink (...) { ... } }; returnDirectivedefinitionobject;});

The compile and link options are mutually exclusive. If both options are set, the function returned by compile is treated as a link function, and the link option itself is ignored.

The compilation function is responsible for converting the template dom. The link function is responsible for linking the scope and the DOM.

The above demo some of the properties in the actual operation, are to take the default properties, then the official website simplifies it into this way:

var mymodule = angular.module (...); Mymodule.directive ('directivename'/// here to note that when the view is introduced to the directive, the camel nomenclature is used, So the call should be Directive-name  var directivedefinitionobject = {    link:function postlink (Scope, IElement, Iattrs) {...}  };   return directivedefinitionobject;   // or   // return function Postlink (scope, ielement, Iattrs) {...}});
View Code

Here still need to write some demo, in order to play the effect of learning!

In the previous study note-ANGULARJS (eight) there is a custom form validation demo, the scenario is that, in the input box can not write "Xiaobin", mainly on the Ngmodel $setValidity ( Validationerrorkey, isValid); and $setViewValue (value, trigger); In the two-way binding is how to implement the Scope->view, view->scope between the verification and formatting of the study, have not seen, you can go to see, although the understanding is not thorough! Here's the main code:

varCustom = Angular.module (' CustomControl ', [' ngsanitize ')]); Custom.directive ("Noxiaobin",function () {return{restrict:A, require:"? Ngmodel", Link:function(scope, element, Attrs, Ngmodel) {if(!ngmodel)return; Ngmodel. $parsers. Push (function(v) {//the Legendary authenticatorif(v! = "Xiaobin") {Ngmodel. $setValidity (' Noxiaobin ',true);//by getting the values coming from the DOM, then validating, using $setvalidity (' Noxiaobin ', true), changing the value of the Noxiaobin, and then feedback the DOMreturnv;} Else{Ngmodel. $setValidity (' Noxiaobin ',false);return(Undefined;}});}} );
View Code

Here, we also write a more comprehensive example, dialog.html can be downloaded to GitHub (GitHub address: https://github.com/xiaobin5201314/AngularJS-Learning/tree/ master/block-example/Command-13)

<!doctype html>'Directivemodule'> "UTF8"/> <script src=".. /jquery.js"></script> <script src=".. /angular.js"></script> <script src=".. /bootstrap.min.js"></script> <link rel="stylesheet"href=".. /bootstrap.min.css"> <script>vardirective = Angular.module ('Directivemodule', []); //Here is the scope of the external directives that can be accessed internally by the validation instructions so that we can also view the traversed Arrs in dialog.htmlDirective.controller ("Directivecontrol",["$scope", Function ($scope) {$scope. Arrs=["I am the content of a","I am content two","I was content three"]; $scope. Hide=false; }])            //By injecting any of the NG services that can be injected into the controller, you can use it in the instruction. There are also special services in the controller that can be injected into the instructions, which are either declared on the application or written directly on the Controllers property .Directive.controller ("Directivechildcontrol",['$scope','$attrs','$element','$transclude', function ($scope, $attrs, $element, $transclude) {$element. css ('Border','#fff');//change the structure inside the template Dom$transclude (function (clone) {//This is the DOM inside the operation's embedded scope                     varA = Angular.element ('<a>'); A.attr ('href','Http://www.cnblogs.com/wuxiaobin'); A.text ('my blog's original address'); $element. Find ('. Modal-body'). append (a);            }); }]) Directive.directive ("Dialog", function () {return{restrict:"AE", replace:true, transclude:true,//when used with Ng-transclude, when True, the contents of the original element (HTML, other instructions) can be extracted to an element with directive NgtranscludeController'Directivechildcontrol', scope:{title:"@" //The template can also access the outer scope object, and dialog.html {{title}} is the result of local scope access to the parent scope, which can well implement the design idea of our component, but it does not understand the writing of @, =, &. Hope to have better learning materials can provide, of course, understand, will also be updated up}, Templateurl:'dialog.html', link:function (scope, element, Attrs, ctrl) {Console.log (element.html ()                        ); Element.find ('. Modal-title'). CSS ('Color','Red');                    }             }             }); </script> "Directivecontrol"> <buttonclass="btn Btn-lg btn-primary"data-toggle="modal"data-target="#myModal"> Pop-up modal frame </button> <dialog title="I'm the title of the pass."> <span ng-repeat="arr in Arrs"Ng-hide="Hide">{{$index}}-{{arr}} <br> </span>my content is about to be saved and extracted to<code> Span[ng-transclude] </code>on</dialog> </body>

Study notes-angularjs (10)

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.