In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to use AngularJS instructions, the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.
Directives is the most important part of all AngularJS applications. Although AngularJS already provides a wealth of instructions, it is often necessary to create application-specific instructions. This tutorial will show you how to customize directives and how to use them in real-world projects. In the second part of this article, I will show you how to use the Angular instruction to create a simple notepad application.
Overview
An instruction is used to introduce a new HTML syntax. An instruction is a tag on an DOM element that gives the element a specific behavior. For example, a static HTML doesn't know how to create and present a date selector control. For HTML to recognize this syntax, we need to use instructions. Directive creates an element that supports date selection in some way. We will introduce how this is achieved step by step. If you've ever written an AngularJS app, you must have used instructions, whether you realize it or not. You must have used simple instructions such as ng-mode, ng-repeat, ng-show, etc. These instructions assign specific behavior to the DOM element. For example, ng-repeat repeats a specific element, and ng-show conditionally displays an element. If you want an element to support drag and drop, you also need to create an instruction to implement it. The basic idea behind the instruction is simple. It makes HTML truly interactive by listening for element binding events or changing the DOM.
JQuery perspective
Imagine how to create a date selector using jQuery. First, we add a normal input box to HTML, and then call $(element) .dataPicker () through jQuery to turn it into a date selector. But think about it. When a designer comes to check the HTML tag, can he or she immediately guess what this field actually represents? Is this just a simple input box or a date selector? You need to check the jQuery code to determine this. Angular's approach is to extend HTML with an instruction. Therefore, the instruction of a date selector can be in the following form:
Or something like this:
This way of creating UI builds is more straightforward and clear. You can easily see what this is by looking at the elements.
Create a custom directive:
An Angular instruction can be expressed in the following four forms: 1. A new HTML element () 2. Attribute of element () 3. CSS class () 4. Note () of course, we can control how our instructions behave in HTML. Let's take a look at the writing of a typical instruction in AngularJS. Instructions are registered in the same way as controller, but it returns a simple object (instruction definition object) that has instruction configuration properties. The following code is a simple Hello World instruction.
Var app = angular.module ('myapp', []); app.directive (' helloWorld', function () {return {restrict: 'AE', replace:' true', template: 'Hello Worldworkers'};})
In the above code, the app.directive () method registers a new instruction in the module. The * argument to this method is the name of the instruction. The second argument is a function that returns the instruction definition object. If your instructions depend on other objects or services, such as $rootScope, $http, or $compile, they can be injected at this time. This directive is used as an element in HTML, as follows:
/ / OR
Or, use it as an attribute:
/ / OR
If you want to conform to the HTML5 specification, you can prefix the element with x-or data-. So the following tag also matches the helloWorld instruction:
/ / OR
Note: when matching instructions, Angular removes the x-or data- prefix from the name of the element or attribute. Then-or: the concatenated string is converted to a camelCase representation, and then matched with the registered instruction. This is why we use the helloWorld directive as hello-world in HTML. In fact, this has something to do with the fact that HTML is case-insensitive to tags and attributes. Although the above instructions only achieve the display of static text, there are still some interesting points worth digging. We used three attributes to configure the directive during the instruction definition process. Let's introduce their roles one by one.
Restrict-this attribute is used to specify how instructions are used in HTML (remember the four representations of instructions mentioned earlier). In the above example, we used 'AE'. So this instruction can be used as a new HTML element or attribute. If we want to allow instructions to be used as class, we set restrict to 'AEC'.
Template-this attribute specifies the HTML tag that is generated after the instruction is compiled and linked (link) by Angular. This property value does not have to be a simple string. Template can be very complex and often contain other instructions, as well as expressions ({{}}), etc. You may see templateUrl more often than template. So, ideally, you should put the template in a specific HTML file and point the templateUrl attribute to it.
Replace-this attribute indicates whether the generated HTML content replaces the HTML element that defines this directive. In our example, we use our instructions in the same way and set replace to true. Therefore, after the instruction is compiled, the generated template content is replaced. The final output is Hello Worldwide!. If you set replace to false, which is the default value, the generated template will be inserted into the element that defines the instruction.
Open the plunker in "Hello Worldwide!" Right-click to check the content of the element to understand this more vividly.
Link function and Scope
The template generated by the directive doesn't really make much sense unless it is compiled under a specific scope. By default, the directive does not create a new child scope. What's more, it uses the parent scope. That is, if the instruction exists under a controller, it uses the scope of that controller. How to use scope, we need to use a function called link. It is configured by the link property in the directive definition object. Let's change our helloWorld directive. When the user enters the name of a color in an input box, the background color of the Hello World text changes automatically. At the same time, the background color changes back to white when the user clicks on the Hello World text. The corresponding HTML tags are as follows:
The modified helloWorld directive is as follows:
App.directive ('helloWorld', function () {return {restrict:' AE', replace: true, template: 'Hello World', link: function (scope, elem, attrs) {elem.bind (' click', function () {elem.css ('background-color',' white'); scope.$apply (function () {scope.color = "white") ); elem.bind ('mouseover', function () {elem.css (' cursor', 'pointer');});}};})
We notice the link function in the instruction definition. It has three parameters:
Scope-scope of the instruction. In our example, the scope of the instruction is the scope of the parent controller.
Elem-the jQLite of the instruction (a subset of jQuery) wraps the DOM element. If you introduced jQuery before you introduced AngularJS, then this element is the jQuery element, not the jQLite element. Because this element is already wrapped by jQuery/jQLite, we no longer need to use $() to wrap it when we do the DOM operation.
Attr-A standardized parameter object that contains the attributes of the element in which the instruction resides. For example, you add some attributes to a HTML element: then you can use it through attrs.someAttribute in the link function.
The link function is mainly used to add event listeners to DOM elements, to monitor changes in model properties, and to update DOM. In the above instruction snippet, we added two events, click, and mouseover. The click handler is used to reset
While the mouseover handler changes the mouse to pointer There is an expression {{color}} in the template that is used to change the background color of the Hello World text when the color in the parent scope changes. This plunker demonstrates these concepts.
Compile function
The compile function is used to do some DOM modifications before the link function is executed. It receives the following parameters:
TElement-the element in which the instruction is located
Attrs-A standardized list of parameters assigned on the element
Note that the compile function cannot access scope and must return a link function. But if the compile function is not set, you can configure the link function normally (with compile, you cannot use the link,link function to be returned by compile). The compile function can be written as follows:
App.directive ('test', function () {return {compile: function (tElem,attrs) {/ / do optional DOM transformation here return function (scope,elem,attrs) {/ / linking function here};})
In most cases, you only need to use the link function. This is because most instructions only need to consider registering event listeners, monitoring models, and updating DOM, which can be done in the link function. But for instructions like ng-repeat, you need to clone and repeat the DOM element multiple times, which is done by the compile function before the link function executes. This raises the question of why we need two separate functions to complete the generation process, and why can't we just use one? To answer this question well, we need to understand how instructions are compiled in Angular!
How instructions are compiled
When the application boot starts, Angular starts traversing the DOM element using the $compile service. This service searches for instructions in tagged text based on registered instructions. Once all the instructions are recognized, the Angular executes their compile method. As mentioned earlier, the compile method returns a link function that is added to the list of link functions to be executed later. This is called the compilation phase. If an instruction needs to be cloned many times (such as ng-repeat), the compile function is executed only once during the compilation phase, copying the templates, but the link function is executed for each copied instance. So separate treatment, let us have a certain improvement in performance. This also explains why the scope object cannot be accessed in the compile function. After the compilation phase, the linking phase begins. At this stage, all collected link functions will be executed one by one. The template created by the directive is parsed and processed under the correct scope, and then the real DOM node with event response is returned.
Change the Scope of the instruction
By default, the instruction gets the scope of the controller of its parent node. But this does not apply in all cases. If the scope of the parent controller is exposed to the instruction, they can modify the properties of the scope at will. In some cases, your instructions want to be able to add properties and methods that are for internal use only. If we add it to the parent's scope, it will pollute the parent scope. In fact, we still have two options:
A child scope-this scope prototype inherits the child parent scope.
An isolated scope-an isolated scope that does not inherit from the parent scope.
Such a scope can be configured by directing to define the scope property in the object. The following code snippet is an example:
App.directive ('helloWorld', function () {return {scope: true, / / use a child scope that inherits from parent restrict:' AE', replace: 'true', template:' Hello Worldworkers'};})
In the above code, Angular is asked to create a new child scope for the instruction that inherits from the parent socpe. Another option, isolated scope:
App.directive ('helloWorld', function () {return {scope: {}, / / use a new isolated scope restrict:' AE', replace: 'true', template:' Hello Worldworkers'};})
This instruction uses an isolated scope. Isolated scope is very beneficial when we want to create reusable instructions. By using isolated scope, we can ensure that our instructions are self-contained and can be easily plugged into HTML applications. It cannot access the parent's scope internally, which ensures that the parent scope will not be contaminated. In our helloWorld instruction example, if we set scope to {}, the above code will not work. It will create a new isolated scope, then the corresponding expression {{color}} will point to the new scope, whose value will be undefined. Using a quarantined scope does not mean that we cannot access the properties of the parent scope at all. There are actually some techniques that allow us to access the properties of the parent scope and even monitor their changes. We will discuss these techniques in the second part of the instruction series, as well as some more advanced concepts, such as Controller functions.
On how to use AngularJS instructions to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.