ANGULARJS Application Module directive () This method is used to define the instruction,
Angular.module (' myApp ', []). Directive (function ($timeout, Userdefinedservice) { // The instruction definition is placed here });
The directive () method can accept two parameters:
1. Name of the name (string) directive,
2. (function) This function returns an object that defines the entire behavior of the instruction. The $compile service takes advantage of the pair of images returned by this method , which constructs the behavior of the instruction when the DOM invokes the instruction.
Angular.application (' myApp ', []). Directive (function() { return { /c4>// by setting an item to define the instruction, here to overwrite }; });
the factory function of the directive is only called once when the compiler first matches to this instruction. similar to the controller function, we invoke the factory function of the directive by $injetor. Invoke.
The life cycle of the instruction begins with the $compile method and ends with the link method.
Angular.module (' myApp ', []) . Directive (function() { return { Restrict:string, Priority:number, Terminal:boolean, template:string or template Function: function (TElement, Tattrs) {...}, templateurl:string, Replace:boolean or String,
Scope:boolean or Object, Transclude:boolean, Controller: String orfunction(scope, element, Attrs, transclude, Otherinjectables) {...}, controlleras:string, require:string, Link:function(Scope, ielement, Iattrs) {...}, compile://returns an object or Join function, as follows: function(TElement, Tattrs, transclude) {return{pre:function(Scope, ielement, Iattrs, controller) {...}, post:function(Scope, ielement, Iattrs, controller) {...} } //or return functionPostlink (...) { ... } } }; });
The restrict is an optional parameter. directives are declared in the DOM . The default ANGULARJS considers the value of restrict to be a, which is declared as an attribute.
E (elements) <my-directive></my-directive>
A (attribute, default) <div my-directive= "expression" ></div>
C (class name) <div class= "my-directive:expression;" ></div>
M (note) <--directive:my-directive expression---(with spaces at both ends)
These options can be used alone or mixed together:
function () { return// INPUT element or attribute }; }); // the above configuration can be used to declare the directive in the same way as a property or annotation: as an attribute <div my-directive></div> or as an element <my-directive></ My-directive>
Attributes are the most common way to declare instructions because they work in all browsers, including older versions of IE, and do not need to register new tags at the head of the document.
Priority level
The priority parameter can be set to a numeric value. Most directives ignore this parameter, using the default value of 0. Ngrepeat is the highest priority in all built-in directives, and it always runs before other instructions. The main consideration for this setting is performance.
The higher the value, the higher the priority, the first call with the same precedence, the declaration of the first call in the preceding,
Terminal (Boolean, True false) whether to stop running instructions on the current element that are lower than the precedence of this directive. However, instructions with the same priority as the current instruction will still be executed.
Examples of using the terminal parameters are Ngview and ngif. The priority of ngif is slightly higher than ngview, and if the expression value of Ngif is true, Ngview can be executed normally, but if the value of the ngif expression is false, it will not be executed because the Ngview has a lower priority
Template (string or function)? A section of HTML text;? A function that accepts two parameters, the arguments are telement and tattrs, and returns a string representing the template.
If a template string contains multiple DOM elements, or is composed of only a single text node, it must be wrapped
Contained within a parent element. In other words, there must be a root DOM element:
Template: ' \
<div> <--Single root element-->\
<a href= "http://google.com" >click me</a>\
</div>\
Also, note the backslash at the end of each line so that ANGULARJS can parse the multiline string correctly. In the actual production,
A better choice is to use the Templateurl parameter to refer to an external template, because it is a nightmare to read and maintain multiple lines of text.
A string that Templateurl(a string or function) the path to an external HTML file, or a two-parameter function with parameters of telement and Tattrs, and returns a string of the path to an external HTML file.
Either way, the URL of the template will be passed through the AngularJS built-in security layer, especially $getTrustedResourceUrl, which will protect the template from being loaded by untrusted sources.
Asynchronously loading a large number of templates via Ajax will severely slow down the speed of a client application. To avoid delays, the HTML template can be cached before the deployment is applied. Caching is a good choice in most scenarios because Angularjs improves performance by reducing the number of requests. For more information about caching, see Chapter 28th.
After the template is loaded, angularjs caches it to the $templatecache service by default. In actual production, the template can be cached in a JavaScript file that defines the template before it is introduced, so that the template does not need to be loaded through XHR.
Replace if set, the value must be true because the default value is False. The implied value means that the template is inserted as a child element inside the element that invokes the directive:
directive Scope:
$rootScope this particular object is created when Ng-app is declared in the DOM:
<div ng-app= "myApp" ng-init= "Someproperty = ' some data '" ></div><div ng-init= "Siblingproperty = ' more Data ' ">inside Div two<div ng-init=" Athirdproperty "></div></div>
Three properties are set in the app's root scope: Someproperty, Siblingproperty, and Athirdproperty
From here, each instruction in the DOM can be called as follows:
? Invoke the same scope object directly;
? Inherits a new scope object from the current scope object;
? Creates a scope object that is isolated from the current scope.
The first two div is a sibling element and can be accessed through get and set $rootscope. A div inside the second Div can also access the same root scope through get and set.
The scope parameter is optional and can be set to TRUE or to an object. The default value is False.
When scope is set to true, a new scope object is inherited from the parent scope and created.
Built-in directive Ng-controller is the function of inheriting from the parent scope and creating a new child scope. It creates a new child scope that inherits from the parent scope.
Isolation scope:
Creating a directive with an isolation scope requires setting the scope property to an empty object {}. If you do this, the template for the directive cannot access the external scope:
The primary usage scenario for directives with isolation scopes 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
<div ng-controller= ' Maincontroller ' > Outside mydirective: {{myproperty}} <div my-directive ng-init= "MyProperty = ' Wow, this is cool '" > Inside mydirective: {{myproperty}} </div> </ Div> var app = Angular.module ("app", []), App.controller (' Maincontroller ', function($scope) {}). directive (' mydirective ', function() { return {restrict: ' A ', scope: {}, Template: ' <div> Inside mydirective {{myproperty}}</div> '//myproperty cannot access myproperty here };});
Binding policy:
ANGULARJS provides several ways to bind the internal isolation scope of the directive to the scope outside of the directive.
Local Scope Properties: Use the @ symbol to bind the local scope to the value of the DOM property. Internal scope of directives can use variables of outer scope, @ (or @attr)
Two-way binding: by = You can make two-way data binding on properties on a local scope's property on the half-level scope. = (or =attr)
Parent scope bindings through the & symbol, you can bind the parent scope to run the function in it. & (or &attr)
<div ng-app= "app" ng-controller= "TestControl" > <drink test= "{{water}}"/></drink> </div>var app = Angular.module ("app", []); App.controller (' TestControl ', function($scope) { $ Scope.water = "Test";}). directive (' Drink ', function() { return { restrict: ' E ', scope:{Test: ' @ ' }, Template: ' < Div>inside--mydirective {{test}} </div> ' };});
The transclude is an optional parameter. If set, its value must be true, and its default value is False.
Embedding is often used to create reusable components, typical examples are modal dialogs or navigation bars
<div sidebox title= "Links" > <ul> <li>first link</li> <li>second link< /li> </ul> </div>app.directive (' sidebox ', function () { return { Restrict: ' EA ', transclude:true, scope:{ title: ' @ ' }, Template: ' <div class= ' Content ' > <span class= ' content ' ng-transclude>\// At this point, Ng-transclude represents the contents of the preceding template </span> </div> " }}";
The controller parameter can be a string or a function. When set to a string, the value of the string is used as the name to find the constructor of the controller registered in the application:
Angular.module (' myApp ', []). directive (' mydirective ', function () {restrict: ' A ',//always requires controller: ' Someco Ntroller '})//Other places in the application, can be the same file or another file contained by index.html Angular.module (' myApp '). Controller (' Somecontroller ' , function ($scope, $element, $attrs, $transclude) {//Controller logic put here});
Or, an inline controller is defined inside the instruction by means of an anonymous constructor:
Angular.module (' myApp ', []). directive (' mydirective ', function () {
Return {restrict: ' A ', Controller:function ($scope, $element, $attrs, $transclude) { Controller logic is put here }
}});
1. $scope The current scope associated with the instruction element.
2. $element The element that corresponds to the current instruction.
3. $attrs An object that consists of the attributes of the current element. <div id= "Adiv" class= "box" ></div> has the following properties: { id: "Adiv", Class: "Box" }
4. $transclude Embedded link function is pre-bound to the corresponding embedding scope. Transclude link functions are functions that are actually executed to clone elements and manipulate the DOM
You want to add a hyperlink tag through a directive. Can be implemented in the $transclude function within the controller ,
<div link > A test </div>app.directive (' link ', function () { return { restrict: ' EA ', transclude:true, controller:function ($scope, $element, $transclude, $log) { $transclude (function ( Clone) { //At this time clone represents the current element var a = angular.element (' <a> '); a.attr (' href ', clone.text ()); A.text (Clone.text ()); $log. Info ("Created new a tag in link Directive"); $element. append (a);}); } };});
The controller of the instruction and the link function can be interchanged. The controller is primarily used to provide behavior that can be reused between instructions, but the link function can only define the behavior in the current internal instruction and cannot be reused between instructions.
The link function isolates the instructions from each other, while the controller defines the reusable behavior.
If you want to expose the API of the current instruction to other directives, you can use the controller parameter, or you can use link to construct the functionality of the current instruction element. If we use scope. $watch () or want to interact with DOM elements in real time, using links is a better choice
When you want to interact with a scope on the current screen, you can use the scope parameter that is passed into the link function, and in some cases, such as embedding, the scope in the controller reflects a different scope than we expected, in which case the $scope object cannot be guaranteed to be updated normally
The Controlleras parameter sets the controller's alias, which can be used as the name to publish the controller, and the scope can access the Controlleras. This allows the controller to be referenced in the view, even without the need to inject $scope.
This example remains to be confirmed:
App.directive (' mydirective ', function () {return {restrict: ' A ', Template: ' , Controlleras: ' Mycontroller ', Controller:function () {this.msg = "Hell O World "//Without $scope, at which time this replaces $scope }});
The Require parameter can be set to a string or an array, and the string represents the name of another instruction. (require means the controller or other instruction on which the instruction is dependent) require injects the controller into the instruction specified by its value and acts as the fourth parameter of the link function of the current instruction.
If you do not use the ^ prefix, the instruction will only look for the controller on its own element. Require: ' ngmodel ' directive definition will only look for ng-model= "" defined in the instruction as the current domain.
The <!--command looks for Ng-model in the local scope--
<div my-directive ng-model= "Object" ></div>
The value of the require parameter can be decorated with the following prefix, which alters the behavior of the lookup controller:
? If the required controller is not found in the current instruction, NULL is used as the fourth parameter passed to the link function.
^ If the ^ prefix is added, the directive looks for the controller specified by the require parameter in the upstream instruction chain.
^ We can optionally load the required instructions and find them in the parent instruction chain.
Without a prefix, if there is no prefix, the instruction will be found in the controller provided by itself and an error will be thrown if no controller (or an instruction with the specified name) is located.
These two want to see:
The instruction uses a sub-scope book in chapter 9th 9. The 2 section transmits the data to the instruction in the 8th chapter of the Book 8. 2 knots
Angular instruction System (ii) custom directives: