AngularJS-Custom Directives

Source: Internet
Author: User

This article, starting from a custom directive , records various factors that affect the behavior of an instruction when defining an instruction.
Try to feel these factors and make yourself more productive in writing ANGULARJS applications.

Directive

Start by defining a simple instruction. Defining a directive is essentially adding functionality in HTML through elements, attributes, classes, or annotations.
Angularjs's built-in directives are all at the ng beginning, and if you want to customize the instructions, it is recommended that you customize a prefix to represent your own namespace.
Here we first use the my prefix as:

var myApp = angular.module(‘myApp‘, [])    .directive(‘myDirective‘, function() {    return {        restrict: ‘A‘,        replace: true,        template: ‘<p>Kavlez</p>‘    };})


In this way, we can use this, noting that the name is camel-case:

<my-directive /><!-- <my-directive><p>Kavlez</p></my-directive> -->


directive()Accepts two parameters

    • Name: string, instruction names
    • Factory_function: function, instruction behavior

When the app starts, the object returned by Factory_function is registered with name as the identity of the app.

In Factory_function, we can set some options to change the behavior of the instruction.

The following records the options used to define the directive

Restrict (String)

This property is used to define what form of instruction is used, which is an optional parameter, and the directive defined at the beginning of this article is a, in fact, the option defaults to a.
That is, Element (E), attribute (A), Class (C), note (M)
(Ps:emac?) Emacs? Very good to remember ha)
As defined above myDirective , can be called in any form.

    • E (Element)

      <my-directive></my-directive>
    • A (property, default)

      <div my-directive="expression"></div>
    • C (class name)

      <div class="my-directive:expression;"></div>
    • M (note)

      <--directive:my-directive expression-->
Priority (number)

That is, the priority, which defaults to 0.
When multiple instructions are declared on the same element, whichever is called first is determined by the priority.
If the priority is the same, it is called in declaration order.
In addition, no-repeat it is the highest priority in all built-in directives.

Terminal (Boolean)

Terminal? And it's a Boolean?
Was frightened by the name, in fact terminal means whether to stop the current element on the lower priority than the instruction. But the same priority will still be executed.
For example, we my-directive add an instruction on the basis of:

.directive(‘momDirective‘,function($rootScope){    return{        priority:3,        terminal:true    };})

Call Discovery my-directive does not take effect:

<div mom-directive my-directive="content" ></div>
Template (String/function)

At least you have to output something, right? But the template is also optional.
When a string type, the template can be a piece of HTML.
function type, the template is one that accepts two parameters, namely:

    • TElement
    • Tattrs

The function returns a string as a template.

Templateurl (string/function)

This is very similar to the template above, but this time it is a URL to request a templates. String type, Templateurl is naturally a URL. function type returns a string as the template URL.

Replace (boolean/string)

The default value is False, as an example of an instruction defined at the beginning of the article, assuming that we call the directive

<my-directive></my-directive>  

When replace is true, the output:

<p>Kavlez</p>

When replace is false, the output:

<my-directive><p>Kavlez</p></my-directive>      
Transclude (Boolean)

This option defaults to False, which translates to ' embedding ' and feels somewhat jerky.
templateAnd scope already can do a lot of things, but there is a little deficiency.
For example, to add content based on the original elements, transclude The example is as follows:

<body ng-app="myApp">    <textarea ng-model="content"></textarea>    <div my-directive title="Kavlez">        

found that the div under the HR is not removed, this is the effect.
Be careful not to forget to declare it in the template ng-transclude .

Scope (Boolean/object)

The default is False,true, which inherits from the parent scope and creates a scope of its own.
ng-controllerthe effect is to inherit from the parent scope and create a new scope.
For example, by leaving your scope, you will be back to the original:

<div ng-init="content=‘from root‘">    {{content}}    <div ng-controller="AncestorController">        {{content}}             <div ng-controller="ChildController">            {{content}}             </div>        {{content}}     </div>    {{content}} </div>.controller(‘ChildController‘, function($scope) {    $scope.content = ‘from child‘;}).controller(‘AncestorController‘, function($scope) {    $scope.content = ‘from ancestor‘;})


But do not misunderstand that the command nesting does not necessarily change its scope.
Now that true you inherit from the parent scope and create a scope of your own, let's try instead what it false looks like:

<div ng-init="myProperty=‘test‘">    {{ myProperty }}    <div my-directive ng-init="myProperty = ‘by my-directive‘">        {{ myProperty }}    </div>    {{ myProperty }}</div>.directive(‘myDirective‘, function($rootScope) {    return {        scope:false    };})

Obviously, the result is three lines ' by My-directive '.
Not true is False? naive!
In fact, the most troublesome is the isolation scope ,


Let's change the mydirective a little bit and switch to output <p>{{内容}}</p> .
So I try to define this:

<body ng-app="myApp" >    <p ng-controller="myController">    <div my-directive="I have to leave." ></div>        {{myDirective}}    </p></body><script type="text/javascript">var myApp = angular.module(‘myApp‘, []).directive(‘myDirective‘, function($rootScope) {    $rootScope.myDirective = ‘from rootScope‘;    return {        priority:1000,        restrict: ‘A‘,        replace: true,        scope: {            myDirective: ‘@‘,        },        template: ‘<p>{{myDirective}}</p>‘    };}).controller(‘myController‘,function($scope){    $scope.myDirective = ‘from controller‘;});</script>



It is important to note that the @ focus is on the isolation scope .
Based on the above example output, the template {{myDirective}} does not affect other scopes.
Let's try this again:

<input type="text" ng-model="content"><p ng-controller="myController" ><div my-directive="{{content}}" ></div>    {{content}}</p>  

Discover that everyone is changing together, that is, the value is passed to the isolation scope by copying the DOM properties.
ng-modelis a powerful instruction that connects its own isolation scope with the DOM scope, which is a two-way data binding.


How to pass data to the isolation scope of a directive is used here @ .
Or it can be written, that is, to @myDirective change a name or something, such as what I use @myCafe to give mydirective assignment is no problem, in short, and the DOM attribute binding.

In addition, we can use bidirectional binding to bind properties of the = property of the local scope to the second-level scope of the domain.
For example, the contents of the isolation scope can only be ' abc ':

<body ng-app="myApp" ng-init="content=‘abc‘">    <p ng-controller="myController" >        <input type="text" ng-model="content">        <div my-directive="content" ></div>        {{content}}    </p></body><script type="text/javascript">var myApp = angular.module(‘myApp‘, []).directive(‘myDirective‘, function($rootScope) {    return {        priority:1000,        restrict: ‘A‘,        replace: true,        scope: {            myDirective: ‘=‘,        },        template: ‘<p>from myDirective:{{myDirective}}</p>‘    };})  .controller(‘myController‘,function($scope){    $scope.content = ‘from controller‘;});</script>
Controller (string/function)

The controller can also be defined in the instructions, such as:

.directive(‘myDirective‘, function() {    restrict: ‘A‘,    controller: ‘myController‘}).controller(‘myController‘, function($scope, $element, $attrs,$transclude) {    //...})

The same effect, you can also declare this:

directive(‘myDirective‘, function() {    restrict: ‘A‘,    controller:function($scope, $element, $attrs, $transclude) {        //...    }});
Controlleras (String)

Can be seen from the name and type, this option is used to set the controller alias.
such as this:

directive(‘myDirective‘, function() {    return {        restrict: ‘A‘,        template: ‘<p>{{ myController.name }}</p>‘,        controllerAs: ‘myController‘,        controller: function() {            this.name = "Kavlez"        }    };});
Compile (object/function)

Although this thing is not very common, but it is worth knowing the option.
compileAnd link , these two options relate to the life cycle of the angularjs.

Here's a simple record of my knowledge of life cycle.

    • All instructions exist as text before the app is started.
    • After the app launches, the compile and linkbegin, and the DOM begins to change and the scope is bound to the HTML.
    • During the compilation phase, ANGULARJS iterates through the entire HTML and processes the declared instructions.
    • Another directive may be used in the template of an instruction, which may contain other instructions, so that layers are a template tree .
    • When the DOM does not have data binding, it is relatively inexpensive to manipulate the DOM, and ng-repeat it is appropriate to manipulate the DOM with instructions like that.
    • We can use the compiled function to access the compiled DOM, and before data binding, the template Dom is transformed with a compiled function, and the compiler returns the template function.
      That is, the significance of setting the compile function is to modify the DOM before the instruction and real-time data are placed in the DOM. The DOM can now be manipulated with no qualms.
    • Then we can go to the next stage, the link stage .
    • Finally, the template function is passed to the instruction-specified link function, which links the scope and the DOM.


Okay, so let's try compile:

<body ng-app="myApp">    <my-directive ng-model="myName"></my-directive></body><script type="text/javascript">var myApp = angular.module(‘myApp‘, []).directive(‘myDirective‘, function($rootScope) {    $rootScope.myName = ‘Kavlez‘;    return {        restrict: ‘EA‘,        compile:function(tEle, tAttrs, transcludeFn) {            var h2 = angular.element(‘

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.