Take you closer to Angularjs-Create custom directives

Source: Internet
Author: User

Why use the ANGULARJS directive?

A friend who has used AngularJS should be most interested in its instructions. The front-end framework on the market today only ANGULARJS has the ability to customize directives, and Angularjs is the only framework that currently provides the reusable capabilities of Web applications.

There are currently many JavaScript products available to Web developers. For example, Bootstrap is currently the most Popular Front-end development kit for providing styles and JavaScript plugins. But when developers use plugins in Booostrap, they must switch to JavaScript mode to write jquery code to activate the plugin although the jquery code is very simple to write, it must be synchronized with HTML, which is a tedious and error-prone process.

The Angularjs home page shows a simple example for the tab function in bootstrap, which makes it easy to add tab functionality to the page and is as simple as using the UL tag. The HTML code is as follows:

<BodyNg-app= "Components">   <H3>BootStrap Tab Component</H3>   <Tabs>     <panetitle= "first Tab">       <Div>This is the content of the first tab.</Div>     </pane>     <panetitle= "Second tab">       <Div>This is the content of the second tab.</Div>     </pane>   </Tabs> </Body>

The JavaScript code is as follows:

Angular.module (' Components ', []). Directive (' Tabs ',function() {     return{restrict:E, transclude:true, scope: {}, Controller: ["$scope",function($scope) {varpanes = $scope. Panes = []; $scope. Select=function(Pane) {Angular.foreach (panes,function(pane) {pane.selected=false;           }); Pane.selected=true; }            This. AddPane =function(pane) {if(Panes.length = = 0) $scope. Select (pane);         Panes.push (pane); }}], Template:' <div class= ' tabbable ' > ' + ' <ul class= ' nav nav-tabs ' > ' + ' <li ng-repeat= ' pane in pane S "ng-class=" {active:pane.selected} "> ' + ' <a href=" "ng-click=" select (pane) ">{{pane.title}}</a&gt ; ' + ' </li> ' + ' </ul> ' + ' <div class= "Tab-content" Ng-transclude></di V> ' + ' </div> ', replace:true     };   }). Directive (' Pane ',function() {     return{require:' ^tabs ', restrict:E, transclude:true, scope: {title:‘@‘}, Link:function(scope, element, Attrs, Tabsctrl) {Tabsctrl.addpane (scope); }, Template:' <div class= ' tab-pane ' ng-class= ' {active:selected} ' ng-transclude> ' + ' </div> ', replace:true     }; })

You can see the effect from the following links: http://jsfiddle.net/powertoolsteam/GBE7N/1/

As you can see, there is no difference between a page and a regular HTML page in addition to having <tabs> and <pane> tags for implementing directives. HTML developers do not need to write any code. Of course, there is always a need to have the first crab-eating person to create instructions for shared use, but the current tabs directives are already common and can be reused anywhere (such as Bootstrap, jQueryUI, Wijmo, and some well-known front-end plug-in sets).

Because of the ease of use and easy writing of instructions, many users have started to write instructions using ANGULARJS. For example, the AngularJS Development Group has implemented a series of directives-ui Bootstrap to replace Bootstrap based on AngularJS, and well-known ComponentOne control vendors have created AngularJS based on Wijmo We can also find some public command repositories on GitHub: jQueryUI widgets.

Have AngularJS, do you feel that you have stood on the shoulders of giants? But don't be happy too early, if you already have so many instructions for us to use, then why do we still have to learn angularjs, why also learn custom directives?

For A simple example, you might have a special need: If you're working in a finance company, you need to create a financial form that needs to present the data in a tabular format, have bindings, edit, validate, and synchronize the data to the server's capabilities. Form plug-ins are common but they are not known to meet these specific needs, so you have to create custom directives based on your actual business needs.

<BodyNg-app= "Abcfinance">   <H3>Offshore Investment Summary</H3>   <Abc-investment-formCustomer= "Currentcustomer"Country= "Currentcountry">   </Abc-investment-form Data> </Body> 

This is the purpose of this article, and we will discuss how to create the ANGULARJS directive.

Create custom Angularjs directives

The custom instructions at the beginning of the article are very simple. It only realizes the function of synchronization. General directives are more elements:

//Create a command module (or retrieve an existing module)varm = Angular.module ("myApp");//Create a "my-dir" directiveMyapp.directive ("MyDir",function() {   return{restrict:"E",//an instruction is an element (not a property)Scope: {//set the scope of the directive forName: "@",//Name Value Pass (string, one-way binding)Amount: "=",//Amount Reference Delivery (bidirectional binding)Save: "&"//Save Operation}, Template://Replace HTML (using variables in scope)"<div>" + "{{name}}: <input ng-model= ' amount '/>" + "<button ng-click= ' Save () ' >save</ Button> "+" </div> ", replace:true,//replace the original tag with a templateTransclude:false,//do not copy original HTML contentController: ["$scope",function($scope) {...}], Link:function(scope, element, Attrs, controller) {...}  } }); 

The effect is as follows:


Note that this custom directive follows a format that is prefixed with "my" and is similar to a namespace, so if you reference multiple module directives in your application, you can easily determine where it is defined by the prefix. This is not a mandatory requirement, but it can bring a lot of convenience.

The constructor of the directive returns a JavaScript object with attributes. The content is clearly stated on the Angularjs home page. Here is my understanding of some of the attributes:

  1. Restrict: Describes how directives are applied in HTML, with alternates "a", "E" and "C", and "M" representing attribute, element, class, and comment (the default value is "a"). We'll focus more on attributes-how to create UI elements.
  2. Scope: Creates the scope of the instruction, and scope is passed as a property label in the directive. Scope is a necessary condition for creating reusable instructions, and each instruction, regardless of the level of the nested instruction, has its own unique scope, and it does not depend on the parent scope. The scope object defines the names and types variables. The above example creates 3 scope variables.
      • Name: "@" (value passing, one-way binding):
        The "@" symbol indicates that the variable is a value pass. The instruction retrieves the value in the string that is passed from the parent scope. Directives can use this value but cannot be modified, which is the most commonly used variable.
      • Amount: "=" (reference, bidirectional binding)
        The "=" symbol indicates that the variable is a reference pass. The instruction retrieves the reference value in the main scope. Values can be of any type, including composite objects and arrays. Directives can change the values in the parent scope, so we need to use this type when the instruction needs to modify the values in the parent scope.
      • Save: "&" (expression)
        The "&" symbol indicates that the variable is an expression that is set to function in the parent scope. It allows the instruction to implement an operation that is more advanced than the modification value.
  3. Template: A string that overrides a tag in the original template. The Replace function replaces all old elements with the new values. Note how the template uses variables that are defined in scope. This allows you to create Macro-style style directives without having to write any extra code. Replace: Indicates whether to replace the value in the original tag or append the value from the original tag. The default value is False, at which point the original tag is preserved.
  4. Transclude: Describes whether the custom directive duplicates the contents of the original tag. For example, the "tab" instruction previously displayed set Transclude to True because the tab element contains other HTML elements. The "dateinput" directive needs to be empty at initialization, so you need to set transclude to false.
  5. Link: This method plays an important role in the instruction. It is responsible for performing DOM operations and registering event listeners. The link method contains the following parameters:
      • Scope: A reference to the directive scope. The scope variable is not defined at initialization time, and the link method registers the monitor to monitor value change events.
      • Element: A reference to the DOM element that contains the instruction, typically through the jquery operation instance (if jquery is not loaded, you can also use angular ' s jqlite).
      • Controller: Used in the case of nested directives. The function of this parameter is that the reference to the handle instruction is provided to the parent instruction, allowing interaction between instructions, and the tab command is the typical example of using this parameter: http://jsfiddle.net/powertoolsteam/GBE7N/1/

Note that when the link method is called, the scope variables passed by value ("@") will not be initialized, they will be initialized at another point in the life of the instruction, and if you need to listen for this event, you can use scope. $watch method.
Well, the above is a description of the basic knowledge required for custom directives. If you are still unfamiliar with instructions, the best way to do this is to implement a few small examples that you can practice in fiddle: http://jsfiddle.net/powertoolsteam/Tk92U/

In the next article we will be familiar with several ANGULARJS custom directives.

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.