The examples in this article describe the usage of AngularJS instructions. Sharing it with you for your reference, the details are as follows:
Directives are the most important components of any AngularJS application. Although AngularJS comes with many directives, you will often find that you need to create some special directives yourself. This article will take you through custom directives and explain how to use them in real-world Angular projects. At the end of the article, we will use Angular instructions to create a simple note-taking application.
Overview
A directive is something that introduces new syntax. Directives are marks made on DOM elements and attached with some specific behaviors. For example, static HTML doesn't know how to create and display a date picker widget. To teach this new syntax to HTML we need a directive. This directive will create an element that acts as a date picker. We will see how to implement this directive later.
If you have written Angular applications before, you have already used directives, whether you realized it or not. You may have used directives like ng-model, ng-repeat, ng-show, etc. All of these directives bind specific functionality to DOM elements. For example, ng-repeat will repeat specific elements, while ng-show will display elements conditionally. If you want to create a draggable element you may need to create a directive. The basic idea behind the directive is simple. It makes HTML interactive by attaching event listeners to elements and transforming the DOM.
Looking at directives from a jQuery perspective
Think about how you would use jQuery to create a date picker. We first add a normal input field in the HTML and then in jQuery we call $(element).dataPicker() to convert it into a date picker. But, think about it. When a designer wants to examine this markup, can he/she immediately guess what this field is for? Is it just a normal input field or a date picker? You'll have to look at jQuery to confirm this. Angular's approach is to use directives to extend HTML. Therefore, a date picker directive might look like this:
<date-picker></date-picker>
or like this:
<input type='text' data-picker/>
This method of creating UI components is both intuitive and clear. You can see an element and know its purpose.
Create custom directives
An Angular directive may appear in four forms:
1. A new HTML element (<date-picker></date-picker>)
2. On an element Attribute ()
3. As a class ()
4. As annotation ()
Of course, we can completely decide how our directive appears in HTML. Now, let's take a look at how a typical Angular directive is written. It is similar to the controller registration method, but it will return a simple object (directive definition), which contains some properties of the configuration directive. The code below shows a simple Hello World directive:
var app = angular.module('myapp',[]); app.directive('helloWorld',function(){ return { restrict: 'AE', replace: true, template: '<h3>Hello World!</h3>' } });
In the code above, the app.diretive() function registers a new directive in our module. The first parameter of this function is the name of the directive. The second parameter is a function that returns the directive definition object. If your directive has dependencies on additional objects/services such as $rootScope, $http or $compile, they can be injected there as well. This directive can be used as an HTML element, as shown below:
<hello-world/>
or:
<hello:world/>
or as an attribute:
<div hello-world></div>
or:
<div hello:world/>
If you want to be compatible with HTML5, you can add x- or data- prefix in front of the attribute. Therefore, the following tags will match the helloWorld directive:
<div data‐hello‐world></div>
or
<di vx‐hello‐world></div>
Note
When matching directives, Angular will remove the x- or data- prefix from element/attribute names. Then convert the delimiter - or : to camelCase notation that matches the registered directive. This is why our helloWorld directive is actually written hello-world when used in HTML.
Although the simple command above just displays some static text, there are still some interesting points worth exploring. We have used three properties in this directive definition object. Let’s take a look at what these three attributes are used for:
restrict - This attribute specifies how a directive should be used in HTML (remember that directives can appear in four ways). In this example we set it to 'AE'. Therefore, this directive can be used as an HTML element or an attribute. To allow the directive to be used as a class we can set restrict to 'AEC'.
template - 這個(gè)實(shí)行指明了當(dāng)指令被Angular編譯和鏈接時(shí)生成的HTML標(biāo)記。它不一定是一個(gè)簡(jiǎn)單的字符串。template可以很復(fù)雜,其中經(jīng)常會(huì)涉及其它的指令,表達(dá)式({{}}),等等。在大多數(shù)情況下你可能會(huì)想要使用templateUrl而不是template。因此,理想情況下你應(yīng)該首先將模板放置在一個(gè)單獨(dú)的HTML文件中然后讓templateUrl指向它。
replace - 這個(gè)屬性指明了是否生成的模板會(huì)代替綁定指令的元素。在前面的例子中我們?cè)贖TML中使用指令為
Hello World!
。如果你將replace設(shè)置為false,默認(rèn)情況下,輸出模板將會(huì)被插入到指令被調(diào)用的元素中。link函數(shù)和作用域
有一個(gè)指令生成的模板是沒有用的除非它在正確的作用域中北編譯。默認(rèn)情況下一個(gè)指令并不會(huì)得到一個(gè)新的子作用域。然而,它可以得到父作用域。這意味著如果一個(gè)指令位于在一個(gè)控制器中那么它將使用控制器的作用域。
為了利用作用域,我們可以使用一個(gè)叫做link的函數(shù)。它可以通過(guò)指令定義對(duì)象中的link屬性來(lái)配置。我們現(xiàn)在對(duì)helloworld指令做一些修改一遍當(dāng)用戶在一個(gè)input字段中輸入一個(gè)顏色名稱時(shí),Hello Wolld文字的背景顏色會(huì)自動(dòng)發(fā)生改變。同樣,當(dāng)一個(gè)用戶點(diǎn)擊Hello World文字時(shí),背景顏色會(huì)重置為白色。相應(yīng)的HTML標(biāo)記如下所示:
<body ng-controller='MainCtrl'> <input type='text' ng-model='color' placeholder='Enter a color' / > <hello-wolrd/> </body>
修改后的helloWorld指令代碼如下所示:
app.directive('helloWorld',function(){ return { restrict: 'AE', replace: true, template: '<p style="background-color:{{color}}"></p>', link: function(scope,elem,attr){ elem.bind('click',function(){ elem.css('background-color','white'); scope.$apply(function(){ scope.color = "white"; }); }); elem.bind('mouseover',function(){ elem.css('cursor','pointer'); }); } } });
注意到link函數(shù)被用在了指令中。它接收三個(gè)參數(shù):
scope - 它代表指令被使用的作用域。在上面的例子中它等同于符控制器的作用域。
elem - 它代表綁定指令的元素的jQlite(jQuery的一個(gè)自己)包裹元素。如果你在AngularJS被包含之前就包括了jQuery,那么它將變成jQuery包裹元素。由于該元素已經(jīng)被jQuery/jQlite包裹,我們沒有必要將它包含在$()中來(lái)進(jìn)行DOM操作。
attars - 它代表綁定指令的元素上的屬性。例如,如果你在HTML元素上有一些指令形式為:
link函數(shù)主要是用來(lái)對(duì)DOM元素綁定事件監(jiān)聽器,監(jiān)視模型屬性變化,并更新DOM。在前面的指令代碼中,我們綁定了兩個(gè)監(jiān)聽器,click和mouseover。click處理函數(shù)重置了
的背景顏色,而mouseover處理函數(shù)則將游標(biāo)改變?yōu)閜ointer。模板中擁有表達(dá)式{{color}},它將隨著父作用域中的模型color的變化而變化,從而改變了Hello World的背景色。
Compile函數(shù)
Compile函數(shù)主要用來(lái)在link函數(shù)運(yùn)行之前進(jìn)行一些DOM轉(zhuǎn)化。它接收下面幾個(gè)參數(shù):
tElement - 指令綁定的元素
attrs - 元素上聲明的屬性
這里要注意compile不能夠訪問(wèn)scope,而且必須返回一個(gè)link函數(shù)。但是,如果沒有compile函數(shù)以依然可以配置link函數(shù)。compile函數(shù)可以被寫成下面的樣子:
app.directive('test',function(){ return { compile: function(tElem,attrs){ //在這里原則性的做一些DOM轉(zhuǎn)換 return function(scope,elem,attrs){ //這里編寫link函數(shù) } } } });
大多數(shù)時(shí)候,你僅僅只需要編寫link函數(shù)。這是因?yàn)榇蟛糠种噶疃贾魂P(guān)心與注冊(cè)事件監(jiān)聽器,監(jiān)視器,更新DOM等等,它們?cè)趌ink函數(shù)中即可完成。像是ng-repeat這樣的指令,需要多次克隆并重復(fù)DOM元素,就需要在link函數(shù)運(yùn)行之前使用compile函數(shù)。你可能會(huì)問(wèn)威懾呢么要將兩個(gè)函數(shù)分別使用。為什么我們不能只編寫一個(gè)函數(shù)?為了回答這個(gè)問(wèn)題我們需要理解Angular是如何編譯指令的!
指令是如何被編譯的
當(dāng)應(yīng)用在啟動(dòng)時(shí),Angular開始使用$compile服務(wù)解析DOM。這項(xiàng)服務(wù)會(huì)在標(biāo)記中尋找指令然后將它們各自匹配到注冊(cè)的適齡。一旦所有的指令都已經(jīng)被識(shí)別完成,Angular就開始執(zhí)行它們的compile函數(shù)。正如前面所提到的,compile函數(shù)返回一個(gè)link函數(shù),該函數(shù)會(huì)被添加到稍后執(zhí)行的link函數(shù)隊(duì)列中。這叫做編譯階段(compile phase)。注意到即使同一個(gè)指令有幾個(gè)實(shí)例存在,compile函數(shù)也只會(huì)運(yùn)行一次。
在編譯階段之后就到了鏈接階段(link phase),這時(shí)link函數(shù)就一個(gè)接一個(gè)的執(zhí)行。在這個(gè)階段中模板被生成,指令被運(yùn)用到正確的作用域,DOM元素上開始有了事件監(jiān)聽器。不像是compile函數(shù),lin函數(shù)會(huì)對(duì)每個(gè)指令的實(shí)例都執(zhí)行一次。
改變指令的作用域
默認(rèn)情況下指令應(yīng)該訪問(wèn)父作用域。但是我們并不像對(duì)所有情況一概而論。如果我們對(duì)指令暴露了父控制器的scope,那么指令就可以自由的修改scope屬性。在一些情況下你的指令可能想要添加一些只有內(nèi)部可以使用的屬性和函數(shù)。如果我們都在父作用域中完成,可能會(huì)污染了父作用域。因此,我們有兩種選擇:
一個(gè)子作用域 - 這個(gè)作用域會(huì)原型繼承父作用域。
一個(gè)隔離的作用域 - 一個(gè)全新的、不繼承、獨(dú)立存在的作用域。
作用域可以由指令定義對(duì)象中的scope屬性定義。下面的例子展示了這一點(diǎn):
app.directive('helloWorld',function(){ return { scope: true, //使用一個(gè)繼承父作用域的自作用域 restrict: 'AE', replace: true, template: '<h3>Hello World!</h3>' } });
上面的代碼要求Angular為指令提供一個(gè)能夠原型繼承父作用域的子組用于。另一種情形,一個(gè)隔離作用域,代碼如下所示:
app.directive('helloWorld',function(){ return { scope: {}, //使用一個(gè)全新的隔離作用域 restrict: 'AE', replace: true, template: '<h3>Hello World!</h3>' } });
? ?
上面的指令使用一個(gè)不繼承父作用域的全新隔離作用域。當(dāng)你想要?jiǎng)?chuàng)建一個(gè)可重用的組件時(shí)隔離作用域是一個(gè)很好的選擇。通過(guò)隔離作用域我們確保指令是自包含的兵可以輕松地插入到任何HTML app中。這種做法防止了父作用域被污染,由于它不可訪問(wèn)父作用域。在我們修改后的helloWorld指令中如果你將scope設(shè)置為{},那么代碼就不會(huì)再正常運(yùn)行。它將創(chuàng)建一個(gè)隔離的作用域然后表達(dá)式{{color}}將無(wú)法引用隔離作用域中的屬性因此值變?yōu)閡ndefined。
隔離作用域并不意味著你一點(diǎn)都不能獲取到父作用域中的屬性。有一些技巧可以使你訪問(wèn)父作用域中的屬性同時(shí)監(jiān)聽這些屬性的變化。我們將在后續(xù)文章中提到這種高級(jí)技巧。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

With the continuous development of the Internet, Web applications have become an important part of enterprise information construction and a necessary means of modernization work. In order to make web applications easy to develop, maintain and expand, developers need to choose a technical framework and programming language that suits their development needs. PHP and AngularJS are two very popular web development technologies. They are server-side and client-side solutions respectively. Their combined use can greatly improve the development efficiency and user experience of web applications. Advantages of PHPPHP

With the rapid development of Web technology, Single Page Web Application (SinglePage Application, SPA) has become an increasingly popular Web application model. Compared with traditional multi-page web applications, the biggest advantage of SPA is that the user experience is smoother, and the computing pressure on the server is also greatly reduced. In this article, we will introduce how to build a simple SPA using Flask and AngularJS. Flask is a lightweight Py

With the popularity and development of the Internet, front-end development has become more and more important. As front-end developers, we need to understand and master various development tools and technologies. Among them, PHP and AngularJS are two very useful and popular tools. In this article, we will explain how to use these two tools for front-end development. 1. Introduction to PHP PHP is a popular open source server-side scripting language. It is suitable for web development and can run on web servers and various operating systems. The advantages of PHP are simplicity, speed and convenience

With the popularity of the Internet, more and more people are using the network to transfer and share files. However, due to various reasons, using traditional methods such as FTP for file management cannot meet the needs of modern users. Therefore, establishing an easy-to-use, efficient, and secure online file management platform has become a trend. The online file management platform introduced in this article is based on PHP and AngularJS. It can easily perform file upload, download, edit, delete and other operations, and provides a series of powerful functions, such as file sharing, search,

The content of this article is about the basic introduction to AngularJS. It has certain reference value. Now I share it with you. Friends in need can refer to it.

With the popularity of web applications, the front-end framework AngularJS has become increasingly popular. AngularJS is a JavaScript framework developed by Google that helps you build web applications with dynamic web application capabilities. On the other hand, for backend programming, PHP is a very popular programming language. If you are using PHP for server-side programming, then using PHP with AngularJS will bring more dynamic effects to your website.
