AngularJS Directive II

Source: Internet
Author: User
Tags list of attributes

Instruction detailed
1. Use the directive () method to define the directive
. directive (' mydirective ', function ($timeout, userdefinedservice) {
return {};
});
The method accepts two parameters:
Name (string): The name of the instruction used to refer to a specific instruction in the view
Factory_function (function): This function returns an object that defines the entire behavior of the instruction
When Angularjs launches the application, it takes the first parameter as a string and registers the object returned by the second argument with this string name. You can also return a function instead of an object to define the instruction, which is often referred to as a link transfer function when a function is returned, which allows you to define the link function of the instruction. However, the return function restricts the degree of freedom when defining instructions.
2. Settings options that the directive can use
(1) Restrict (string)
Tell Angularjs what form this directive can be declared in the DOM, including:
E (elements) <my-directive></my-directive>
A (attribute, default) <div my-directive= "expression" ></div>
C (class name) <div class= "my-directive:expression;" ></div>
These options can be mixed, with attributes that declare instructions in the most common way, as it works in all browsers, including older versions of IE, and does not require a new label to be registered at the head of the document.
How you choose, usually depends on whether the defined directive contains the core behavior of a component (E), or modifies or expands a core component with additional behavior, state, or other content (a)
When you write a template that also needs to be used in other directives, you can cache the template, such as:
var myapp=angular.module (' myApp ', []);
Myapp.run (function ($templateCache) {
$templateCache. Put ("index1.html", "<div>hello everyone!</div>");
});
Myapp.directive (' Hello ', function ($templateCache) {
return{
Restrict: ' AE ',
Template: $templateCache. Get (' index1.html '),
Repalce:true
}
})
(2) Priority pripority (numeric)
If an element has two commands with the same precedence, the one declared in front of it will be called first.
Ng-repeat is the highest priority in all instructions, and the other default value is 0, mainly from performance considerations.
(3) Terminal (Boolean type)
This parameter tells Angularjs to stop running an instruction with a lower priority than this instruction on the current element, but an instruction with the same priority will still execute.
(4) Template (string or function)
Must be set to the following two types:
A section of HTML text
b A function that accepts two parameters, TElement and Tattrs, and returns a string representing the template.
There must be a DOM element in the template string, and a backslash at the end of each line guarantees that ANGULARJS correctly parses the multiline string. A better choice is to use the Templateurl parameter to refer to an external template, because multiple lines of text are difficult to read and maintain.
(5) Templateurl
Can be of two types:
A a string representing the path of an external HTML file
b A function that can accept two arguments, TElement and Tattrs, and a string that returns an external HTML file path
An HTML template file is requested by Ajax in the background when the instruction is invoked, and a local server is run in the background to load the HTML template from the file system when it is developed locally. Template loading is asynchronous, meaning that compilation and linking are paused, waiting for template loading to complete.
Asynchronously loading a large number of templates via Ajax will severely slow down the speed of a client application by caching the template in a JS file that defines the template in advance.
(6) Replace (Boolean type)
Setting to True means that the template is inserted as a child element inside the element that calls this directive.
<div some-directive></div>
. directive (' somedirective ', function () {
return{
Template: ' <div>some stuff here</div> '
};
})
Results: <div some-directive><div>some Stuff here</div></div>
After joining Replace:true, the result is: <div>some stuff here</div>
(7) Scope (Boolean or object)
When scope is set to true, a new scope object is inherited from the parent scope and created
The primary scenario for isolation scopes is to create reusable components that can be used in unknown contexts and avoid the external scope or inadvertent contamination of the internal scope of the contamination. Creating a directive with an isolation scope requires setting the scope property to an empty object {}, so that the template for the instruction cannot access the external scope.
<div ng-app= "MYAPP"
ng-init= "Someproperty = ' some data '" ></div>
<div ng-init= "Siblingproperty = ' more Data '" >
Inside Div: {{Athirdproperty}}
<div ng-init= "Athirdproperty = ' data for 3rd '"
Ng-controller= "Somectrl" >
Inside Div Three: {{athirdproperty}}
<div ng-controller= "Secondctrl" >
Inside Div Four: {{athirdproperty}}
<br>
Outside mydirective: {{MyProperty}}
<div my-directive ng-init= "myproperty = ' Wow, this is cool '" >
Inside mydirective: {{MyProperty}}
<div>
</div>
</div>
</div>
Angular.module (' myApp ', [])
. Controller (' Somectrl ', function ($scope) {
We can leave it empty, it just needs to be defined
})
. Controller (' Secondctrl ', function ($scope) {
Also can be empty
})
. directive (' mydirective ', function () {
return {
Restrict: ' A ',
Scope:true
}
})
The result is: Inside Div:
Inside Div Three:data for 3rd property
Inside Div Four:data for 3rd property
Outside Mydirective:wow, this is cool
Inside Mydirective:wow, this is cool
Add scope:true or scope:{} result: Outside mydirective:
Inside Mydirective:wow, this is cool
Cases:
<div ng-conreoller= "Maincontroller" >
Outside mydirective: {{MyProperty}}
<div my-directive ng-init= "myproperty = ' Wow, this is cool '" >
Inside mydirective: {{MyProperty}}
<div>
</div>
Angular.module (' myApp ', [])
. Controller (' Maincontroller ', function ($scope) {
})
. directive (' mydirective ', function () {
return {
Restrict: ' A ',
Scope:true,
PRIORITY:100,
Template: ' <div>inside mydirective:{{myproperty}}</div> '
};
})
Outside mydirective:
Inside Mydirective:wow, this is cool
Cases:
<div ng-init= "MyProperty = ' Wow, this is cool '" ></div>
Surrounding scope: {{MyProperty}}
<div my-inherit-scope-directive= "Somectrl" >
Inside an directive with inherited scope: {{MyProperty}}
</div>
<div my-directive>
Inside mydirective, isolate scope: {{MyProperty}}
<div>
Angular.module (' myApp ', [])
. directive (' mydirective ', function () {
return {
Restrict: ' A ',
Scope: {}
};
})
. directive (' myinheritscopedirective ', function () {
return {
Restrict: ' A ',
Scope:true
};
})
Surrounding Scope:wow, this is cool
Inside an directive with inherited Scope:wow, the is cool
Inside mydirective, isolate scope:
(8) Binding policy
Use a binding policy to bind the inner isolation scope of a directive to a scope outside the directive
A local scope property: @/@attr bind the local scope to the value of the DOM property
b Two-way binding: =/=attr to bind properties on a property on the local scope to the half-level scope
C Parent Scope Binding: &AMP;/&AMP;ATTR When you set this value, a wrapper function that points to the parent scope is generated
Cases:
<div ng-controller= "Myctrl" >
<drink flavor= "{{ctrlflavor}}" ></drink>
</div>
var myapp=angular.module (' myApp ', []);
Myapp.controller (' Myctrl ', [' $scope ', function ($scope) {
$scope. ctrlflavor= "Budweiser";
}]);
Myapp.directive ("Drink", function () {
return{
Restrict: ' AE ',
Template: "<div>{{flavor}}</div>",
Link:function (scope,element,attrs) {
Scope.flavor=attrs.flavor;
}
}
})
Equivalent:
Myapp.directive ("Drink", function () {
return{
Restrict: ' AE ',
scope:{
Flavor: ' @ '
},
Template: "<div>{{flavor}}</div>"
}
})
Cases:
<div ng-controller= "Myctrl" >
Ctrl:<br>
<input type= "text" ng-model= "Ctrlflavor" ><br>
Directive:<br>
<drink flavor= "Ctrlflavor" ></drink>
</div>
var myapp=angular.module (' myApp ', []);
Myapp.controller (' Myctrl ', [' $scope ', function ($scope) {
$scope. ctrlflavor= "Budweiser";
}]);
Myapp.directive ("Drink", function () {
return{
Restrict: ' AE ',
scope:{
Flavor: ' = '
},
Template: ' <input type= ' text "ng-model=" Flavor "/> '
}
})
Modify one and the other will change
(9) Transclude (Boolean type)
Used to create reusable components, the typical example being modal dialogs or navigation bars.
The entire template, including its directives, can be embedded in a single directive. In order to pass the scope in, the value of the scope parameter must be set to the isolation scope by {} or True.
(Ten) Controller (string or function)
Angular.module (' MyApp ', [])
. directive (' mydirective ', function () {
Restrict: ' A ',
Controller: ' Somecontroller '
})
Also set the controller in the same file or another file contained in the index.html
Angular.module (' MyApp ', [])
. Controller (' Somecontroller ', function ($scope, $element, $attrs, $transclude) {})
It is also possible to define an inline controller within the directive by means of an anonymous constructor:
Angular.module (' MyApp ', [])
. directive (' mydirective ', function () {
Restrict: ' A ',
Controller:function ($scope, $element, $attrs, $transclude) {
}
})
Any ANGULARJS service that can be injected can be passed to the controller, which can be used in the instruction simply by injecting it into the controller. Some special services can be injected into the directive, including:
$scope: The current scope associated with the directive element
$element: The element that corresponds to the current instruction
$attrs: An object that consists of the attributes of the current element
<div id= "Adiv" class= "box" ></div>
{
ID: "Adiv",
Class: "Box"
}
$transclude: Embedded link function is pre-bound to the corresponding embedding scope
3. The life cycle of the instruction
(1) Load phase: Load Angularjs, find Ng-app, determine application boundary
Compile phase:
Traverse Dom to find all instructions;
Convert the DOM structure according to the template,replace,transclude in the instruction code;
If a complie function is called;
Link stage:
Run the link function on each instruction;
The link function is typically used to manipulate the DOM, bind event listeners, and listen for data changes
(2) Application of link function:
If there is a require option in the directive definition, there will be a fourth parameter in the function signature, which represents the controller or the command-amount controller
Link:function (Scope,element,attrs,somecontroller) {
}
Where the scope directive is used to register the scope of the listener within it, the IElement parameter represents the instance element, refers to the element using this directive, the Iattrs parameter represents the instance attribute, is a normalized list of attributes defined on the element, and can be shared among the link functions of all instructions. The controller parameter points to the controllers defined by the Require option.
<div ng-controller= "Myctrl" >
<loader howtoload= "LoadData ()" > Sliding loading </loader>
</div>
Myapp.directive (' loader ', function () {
return{
Restrict: ' AE ',
Link:function (scope,element,attrs) {
Element.bind ("MouseEnter", function () {
Scope.loaddata ();
Scope. $apply ("LoadData ()");
})
}
};
})
To reuse a command in a different controller:
<div ng-controller= "Myctrl" >
<loader howtoload= "LoadData ()" > Sliding loading </loader>
</div>
<div ng-controller= "MyCtrl2" >
<loader howtoload= "LoadData2 ()" > Sliding loading </loader>
</div>
var myapp=angular.module (' myApp ', []);
Myapp.controller (' Myctrl ', [' $scope ', function ($scope) {
$scope. Loaddata=function () {
Console.log (' 111 ' in data loading);
}
}]);
Myapp.controller (' MyCtrl2 ', [' $scope ', function ($scope) {
$scope. Loaddata2=function () {
Console.log (' 222 ' in data loading);
}
}]);
Myapp.directive (' loader ', function () {
return{
Restrict: ' AE ',
Link:function (scope,element,attrs) {
Element.bind ("MouseEnter", function () {
Scope. $apply (attrs.howtoload);
})
}
};
})
Re-use of instructions:
<div class= "Row" >
<div class= "Col-md-3" >
<superman strength> Motion Superman </superman>
</div>
<div class= "Col-md-3" >
<superman Strength speed> Dynamic Superman 2---power + agility </superman>
</div>
<div class= "Col-md-3" >
<superman Strength Speed light> Dynamic Superman 3---Power + agility + Glow </superman>
</div>
</div>
var myapp=angular.module (' myApp ', []);
Myapp.directive ("Superman", function () {
return{
scope:{},
Restrict: ' AE ',
Controller:function ($scope) {
$scope. abilities=[];
This.addstrength=function () {
$scope. Abilities.push ("Strength");
};
This.addspeed=function () {
$scope. Abilities.push ("Speed");
};
This.addlight=function () {
$scope. Abilities.push ("Light");
};
},
Link:function (scope,element,attrs) {
Element.addclass (' btn btn-primary ');
Element.bind ("MouseEnter", function () {
Console.log (scope.abilities);
});
}
}
});
Myapp.directive ("Strength", function () {
return{
Require: ' ^superman ',
Link:function (Scope,element,attrs,supermanctrl) {
Supermanctrl.addstrength ();
}
}
});
Myapp.directive ("Speed", function () {
return{
Require: ' ^superman ',
Link:function (Scope,element,attrs,supermanctrl) {
Supermanctrl.addspeed ();
}
}
});
Myapp.directive ("Light", function () {
return{
Require: ' ^superman ',
Link:function (Scope,element,attrs,supermanctrl) {
Supermanctrl.addlight ();
}
}
});
Independent scope:
var myapp=angular.module (' myApp ', []);
Myapp.directive ("Hello", function () {
return{
Restrict: ' AE ',
Template: ' <div><input type= ' text "ng-model=" username "/>
{{username}}</div> ',
Replace:true
}
})
Click one of the input boxes, and all of the input boxes and their subsequent contents change. Just add scope:{}, all the input box contents do not affect each other

AngularJS Directive II

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.