AngularJs (Part 11)--custom directive

Source: Internet
Author: User

Have a rough image of the custom Directive first

Mymodule.directive (' mydirective ',function(injectables) {vardirectivedefinitionobject={restrict:string, Priority:number, template:string, templateurl:string, Replace:bo OL, Transclude:bool, Scope:bool or object, controller:functionControllerconstructor ($scope, $element, $attrs, $transclude) {...}, require:string, Link:functionPostlink (scope,ielement,iattrs) {...}, compile:functionCompile (telement,tattrs,transclude) {...return{Pre:functionlink (Scope,ielement,iattrs,controller) {...}, Post:functionlink (Scope,iele            Ment,iattrs,controller) {...}        }; }    };});
View Code

Focus on Directivedefinitionobject this object. Some of the properties of this object are mutually exclusive, i.e., with the A attribute, no B attribute is required. But most of them are optional.

Here is a detailed explanation of the effects of each property
1. Restrict: The decision Directive is to do HTML tag, attribute, class or comment, can only be in the ' E ', ' A ', ' C ', ' M ' or any combination of these four letters to take value. Refer to the following table
Value Example
E <my-directive></my-directive>
A <div my-directive= ' abc ' ></div>
C <div class= ' my-directive:abc ' ></div>
M <!--This is ABC my-directive:abc--
Restrict default is a, if a directive want to use the tag and also want to use in comments, then use ' EM '
2. Priority setting priorities, the number of first run. An example is ng-repeat, which must run Ng-repeat first, produce duplicate objects, and then run other
3. Template and Templateurl templates or template addresses. Sometimes we wrap a large piece of HTML fragment in a angularjs, such as I just want to use a });
4. transclude sometimes we want to keep the original content and add them to the template, if there are

<div>hello World</div>, then "We had fun" This section is gone, now set transclude to True, and set the template to <div>hello world <span Ng-transclude></span></div&gt, you can achieve the desired effect. Notice there's a ng-transclude in the template.
5.compile and Link
ANGULARJS's directive to work must go through two stages:
1) Compile stage, at this stage Angularjs search the entire DOM tree in the template, find all other registered directive, and convert them to DOM according to their respective templat, replace, etc. function for running the respective compile
2) Link phase, at this stage is mainly responsible for maintaining model and view consistency, is a variety of add listeners. At this stage the scope is injected into the link, and all the directive are useful

...

6.scope Angularjs offers three scopes to directive
1). Use scope (false) that already exists in the DOM
2). Inherit all properties in the parent scope (true) since the scope that already exists
3). An independent scope. The properties of the parent scope cannot be accessed, but he has a $parent property that points to the parent scope (a {/*properties*/} object)
For the first two kinds of nothing to say, for the third, see an example.
Now you want to complete a click and display some div functions. The HTML code is as follows:
<div ng-controller= ' Mycontroller ' >
<expander expand-title= ' title ' expand-text= ' text ' expand-click= ' Change () ' ></expander>
</div>
The JavaScript code is as follows:

Angular.module (' Test ', []). Controller (' Mycontroller ', [' $scope ',function($scope) {$scope. Title= ' Click me I am the title '; $scope. Text= ' Well, I was hidden and now I am shown '; $scope. Change=function() {$scope. Text= ' Haha i change myself ';                            }; }]). directive (' Expander ',function(){            return{restrict:E, replace:true, transclude:true, template:[' <div> ',                            ' <div id= ' D1 "ng-click=" Toggle () ">{{scopeTitle}}</div>",                            ' <div id= ' D2 ' ng-show= ' showMe ' ng-transclude>{{scopetext}}</div> ',                            ' <div id= ' D3 ' ng-click= ' Scopechange () ">click Me to Change</div> ',                          ' </div> '].join (' '), Scope:{scopetitle:' @expandTitle ', Scopetext:' =expandtext ', Scopechange:' &expandclick '}, Link:function(scope,element,attributes) {Scope.showme=false; Scope.toggle=function() {Scope.showme=!Scope.showme;                };        }            }; })        ;
View Code

The

    result is the title shown in D1, because Scopetitle gets the ' @expandTitle ', meaning that the attribute value of Expand-title is passed as a string to scopetitle;

The D2 shows that "Well, I was hidden and now I am shown", because Scopetext obtained is ' =expandtext ', meaning that the value of Expand-text as the variable name, in the parent scope to find a variable with the same name, Pass the value of this variable to scopetext;
Then look at the Ng-click in D3, whose value is passed in Scopechange: ' &expandclick ', the value of Expand-click is the scope method in the parent scope. So ' & ' can be used to pass methods.

4.controller directives need to communicate with each other yes, can be done by controller
Controller:function ($scope, $element, $attrs, $transclude) {}
Other directive can accept this controller: through the Require property require: "^?directivename".
Directivename: Is the name of the directive of the hump notation. The name of which directive controller to write;
^: The default angularjs is to find the same element within the directive, if added "^", angularjs along the DOM tree to look up, know to find so far;
?: If not found Controller,angularjs will throw an error, plus "?" It doesn't matter if you can't find it.
Rewrite An example that requires three tags to appear, click on one of them, expand yourself, and other contractions

Angular.module (' Test ', []). Directive (' Accordion ',function(){            return{restrict:E, replace:true, transclude:true, Template:' <div ng-transclude></div> ', Controller:function(){                    varexpanders=[];  This. getopened=function(selected) {Angular.foreach (expanders,function(Expander) {if(selected!=Expander) {Expander.showme=false;                    }                        });                    };  This. addexpander=function(Expander) {Expanders.push (expander);                };        }            }; }). directive (' Expander ',function(){            return{restrict:E, replace:true, transclude:true, require:"^?accordion", template:[' <div> ',                            ' <div ng-click= ' toggle () ">{{scopeTitle}}</div>",                            ' <div ng-show= ' showMe ' ng-transclude>{{scopetext}}</div> ',                          ' </div> '].join (' '), Scope:{scopetitle:' =expandtitle ', Scopetext:' =expandtext ',}, Link:function(scope,element,attrs,accordioncontroller) {Scope.showme=false;                    Accordioncontroller.addexpander (scope); Scope.toggle=function() {Scope.showme=!Scope.showme;                    accordioncontroller.getopened (scope);                };        }            }; }). controller (' Mycontroller ', [' $scope ',function($scope) {$scope. expanders=[{title:' Click1 ', Text:' Text1 '},{Title:' Click2 ', Text:' Text2 '},{Title:' Click3 ', Text:' Text3 '            }]; }]);
View Code

Look at HTML again:
<div ng-controller= ' Mycontroller ' >
<accordion>
<expander ng-repeat= ' expander in expanders ' expand-title= ' expander.title ' expand-text= ' Expander.text ' ></ Expander>
<accordion>
</div>
As you can imagine, I'm going to implement a feature that expands on other contractions, and I have to have a place to store all the expander states. Although the scope in the expander link can be accessed to the scope of Mycontroller so that expanders can be found, it is best not to do so, or to be isolated. The best place to be stored is in the parent element accordion of Expander. Accordion is the equivalent of a warehouse where he provides APIs for others to use.

AngularJs (Part 11)--custom directive

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.