How to write a custom directive in Angularjs

Source: Internet
Author: User

Directive definition
    • For instructions, it can be simply understood as a function that runs on a particular DOM element, and the instruction extends the function of the element.
    • For example, Ng-click can allow an element to listen for a click event and execute a ANGULARJS expression when an event is received
    • It is the directive that makes the framework of ANGULARJS powerful, and as we can see, we create new instructions ourselves.
Instruction Declaration method
Angular.module (' Freefedapp ', []). Directive (name,function() {      return {            restrict:string,            Priority:number,            Terminal:boolean,            template:string or template function:functionfunction (Scope, ielement, Iattrs) {...},};});      

Instruction Scope

Each instruction in the DOM can be called as follows:

    • Calling the same scope object directly
    • Inherits a new scope object from the current scope object
    • Create a scope object that is isolated from the current scope

Scope scope setting (the parameter is optional and the default value is False):

    • True inherits from the parent scope and creates a new scope object
    • False to invoke the same scope object directly
    • {} Creating a directive with isolation scope, with an isolation scope The primary usage scenario is to create reusable components that can be used in unknown contexts, and can avoid the external scope of contamination or inadvertently pollute the internal scope
Scope Binding Policy

For the directive isolation scope ANGULARJS provides several ways to bind the internal scope of the directive to the scope outside of the directive.

    • The @ (or @attr) binds the directive local scope to the value of the DOM property using the @ symbol, and the internal scope of the instruction can use variables of the outer scope, pure value binding
    • = (or =attr) by = You can have two-way data binding on attributes on the half-scope of the property on the local scopes, just like normal data binding, where the local property reflects the changes that have occurred in the parent data model
    • & (or &attr) can bind a parent scope to run the function in it by using the & symbol. means that setting this value will generate a wrapper function that points to the parent scope, to invoke the parent method with a parameter, we need to pass an object, the key of the object is the name of the parameter, the value is the content to pass to the parameter
Demo.html<!DOCTYPE HTML><HtmlNg-app= "Freefedapp"><Head><Title>angular Application Demo</Title><ScriptSrc= "Angular.js"></Script><ScriptSrc= "App.js"></Script></Head><Body><DivNg-controller= "Freefedctrl">Send e-mail address:<InputType= "Text"Ng-model= "from"/>Receive email Address:<InputType= "Text" Ng-model = "to" /> <div email-directive from-email= " {{from}} ' 

App.js/*Declaring module*/var module = angular.module (' Freefedapp ',[]);/*Declaring a controller*/Module.controller (' Freefedctrl ', [' $scope ',function($scope) {$scope. from = ' [email protected] '; $scope. SendMail =function(email) {alert (' I will send mail to ' +email); };}]);/* declaration directive */module.directive ( ' Emaildirective ', function () { return {scope: {fromemail: ' @ ' // bind to parent scope ", Link: function (scope,el,attr) { Scope.onsend ({email:scope. Toemail}); // OnSend function that calls the parent scope of the sendmail binding and passes the value of the parameter email to it             
Instruction parameter Explanation
  • Restrict:string
    The restrict is an optional parameter. It tells Angularjs what form this instruction can be declared in the DOM. The default angularjs that the value of restrict is a, which is declared as an attribute, and the optional value is as follows: E (Element) A (attribute, default)
    C (class name)
    M (note)
  • Priority:number,
    The priority parameter can be set to a numeric value. Most directives ignore this parameter, using the default value of 0, but also some scenarios where setting high priority is important or even necessary. For example, Ngrepeat sets this parameter to 1000 so that it can be 10 to ensure that it is always called before other instructions on the same element
  • Terminal:boolean,

    这个参数用来告诉angularJS停止运行当前元素上比本指令优先级低的指令。但同当前指令 优先级相同的指令还是会被执行。?如果元素上某个指令设置了terminal参数并具有较高的优先级,就不要再用其他低优先级的 指令对其进行修饰了,因为不会被调用。但是具有相同优先级的指令还是会被继续调用。使用了terminal参数的例子是ngView和ngIf。ngIf的优先级略高于ngView,如果ngIf的表 达式值为true,ngView就可以被正常执行,但如果ngIf表达式的值为false,由于ngView的优先 级较低就不会被执行
  • Template:string or template function:function (TElement, Tattrs) (...},

    template parameter is optional and must be set to one of the following two forms: a piece of HTML text, a function that accepts two parameters, a parameter of TElement and Tattrs, and returns a string representing the template. The T in TElement and tattrs represents the template, which is relative to instance. The differences between a template element or attribute and an instance element or attribute are described in detail when discussing linking and compiling settings. Angularjs handles the template string just as it does with HTML. The scope can be accessed through the braces tag in the template, for example {{expression}}. If a template string contains multiple DOM elements, or is composed of only a single text node, it must be contained within a parent element. In other words, there must be a root DOM element: Template: ' <div> <--single root element---<a href= ' Http://go         Ogle.com ">click me</a>  
  • Templateurl:string,

    templateurl are optional parameters, This can be a string representing the path of an external HTML file, a function that accepts two parameters, a telement and tattrs parameter, and a string that returns an external HTML file path, by default, Invoking the instruction in the background through AJAX to request an HTML template file template loading is asynchronous, meaning that the compilation and link to pause, waiting for the template to load complete. Asynchronously loading a large number of templates via Ajax will severely slow down the speed of a client application. To avoid delays, you can cache an HTML template before you deploy the app. Caching is a good choice in most scenarios because ANGULARJS improves performance by reducing the number of requests. After the template is loaded, angularjs caches it to the $templatecache service by default. In real production, the template can be cached in advance into a JavaScript file that defines the template, so that you do not need to load the template with XHR  
  • Replace:boolean or String,

    replace是一个可选参数,如果设置了这个参数,值必须为true,因为默认值为false。默认值意味着模板会被当作子元素插入到调用此指令的元素内部:     <div some-directive></div>     .directive(‘someDirective‘, function() {             return {                  template: ‘<div>some stuff here<div>‘             };       });调用指令之后的结果如下(这是默认replace为false时的情况):     <div some-directive>         <div>some stuff here<div>     </div> 如果replace被设置为了true:     .directive(‘someDirective‘, function() {             return {                  replace: true // 修饰过??????                  template: ‘<div>some stuff here<div>‘             };      ?});指令调用后的结果将是:     <div>some stuff here<div>
  • Scope:boolean or Object,

    看上面指令作用域
  • Transclude:boolean,

  • Controller:string orfunction (scope, element, Attrs, transclude, Otherinjectables) {...},

    controller参数可以是一个字符串或一个函数。当设置为字符串时,会以字符串的值为名字, 来查找注册在应用中的控制器的构造函数</pre>* controllerAs: String,<pre>controllerAs参数用来设置控制器的别名,可以以此为名来发布控制器,我们可以在路由和指令中创建匿名控制器的强大 能力。这种能力可以将动态的对象创建成为控制器,并且这个对象是隔离的、易于测试的```
    • Require:string,
    • Link:function (Scope, ielement, Iattrs) {...},

      用link函数创建可以操作DOM的指令

How to write a custom directive in Angularjs

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.