<\/body> <\/html>\n<\/pre>\n

Now add the angular.min.js<\/code> file from Google CDN to <\/code> of the document: <\/p>\n

 
	






亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Prepare
Step 1: HTML Template
Step 2: Create module
第 4 步:檢測更改
元素指令:進(jìn)度條
第 1 步:樣式
第 2 步:指令的屬性
第3步:鏈接函數(shù)
第 4 步:使用 jQuery 添加動畫
結(jié)論
有用鏈接
Home CMS Tutorial WordPress Enhance HTML with AngularJS directives

Enhance HTML with AngularJS directives

Aug 27, 2023 am 08:01 AM

使用 AngularJS 指令增強(qiáng) HTML

The main feature of AngularJS is that it allows us to extend the functionality of HTML to serve the purpose of today’s dynamic web pages. In this article, I'll show you how to use AngularJS's directives to make your development faster and easier, and make your code more maintainable.

Prepare

Step 1: HTML Template

To make things easier, we will write all the code in one HTML file. Create it and put a basic HTML template into it:

<!DOCTYPE html> <html> <head> </head> <body> </body> </html>

Now add the angular.min.js file from Google CDN to <head> of the document:

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>

Step 2: Create module

Now let's create the module for the directive. I'll call it example, but you can choose any name you want, just remember that we will use this name as the namespace for the directive we create later.

Put this code in a script tag at the bottom of <head>:

var module = angular.module('example', []);

We don't have any dependencies, so the array in the second parameter of angular.module() is empty, but don't remove it completely or you will get the $injector:nomod error because # The single-argument form of ##angular.module() retrieves a reference to an existing module instead of creating a new module.

You must also add the

ng-app="example" attribute to the <body> tag for the application to work properly. The file should then look like this:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script> <script> var module = angular.module('example', []); </script> 
    </head> 
    <body ng-app="example"> 
    </body> 
</html>

Attribute command: 1337 C0NV3R73R

First, we will create a simple directive that will work similarly to ngBind, but it will change the text to leet talk.

Step 1: Instruction Statement

Use

module.directive() method to declare instructions:

module.directive('exampleBindLeet', function () {

The first parameter is the name of the instruction. It must be in camelCase, but since HTML is not case-sensitive, you will use dash-delimited lowercase (example-bind-leet) in the HTML code.

The function passed as the second parameter must return an object describing the instruction. Currently it has only one attribute: link function:

    return {
		link: link
	};
});

Step 2: Link function

You can define the function before the return statement or directly in the returned object. It is used to manipulate the DOM of the element our directive applies to, and is called with three arguments:

function link($scope, $elem, attrs) {

$scope is an Angular scope object, $elem is the DOM element matched by this directive (it is wrapped in jqLite??e, which is jQuery for AngularJS A subset of the most commonly used functions) attrs is an object with all the element attributes (with canonicalized names, so example-bind-leet will be available as attrs.exampleBindLeet).

The simplest code for this function in our directive looks like this:

    var leetText = attrs.exampleBindLeet.replace(/[abegilostz]/gmi, function (letter) {
	    return leet[letter.toLowerCase()];
    });

	$elem.text(leetText);
}

First, we replace some letters in the text provided in the

example-bind-leet attribute with the replacement content from the leet table. The table looks like this:

var leet = {
    a: '4', b: '8', e: '3',
	g: '6', i: '!', l: '1',
	o: '0', s: '5', t: '7',
	z: '2'
};

You should put it on top of the

<script> tag. As you can see, this is the most basic leet converter since it only replaces ten characters.

Afterwards, we convert the string to leet say, which we use jqLite's

text() method to put into the inner text of the element matched by this directive.

Now you can test this HTML code by placing it in

<body> of your document:

<div example-bind-leet="This text will be converted to leet speak!"></div>

The output should look like this:

But that's not exactly how the

ngBind directive works. We'll change this in the next steps.

Step 3: Scope

First of all, what is passed in the

example-bind-leet attribute should be a reference to the variable in the current scope, not the text we want to convert. To do this, we must create an isolated scope for the directive.

We can achieve this by adding the scope object to the return value of the directive function:

module.directive('exampleBindLeet', function () {
    ...
	return {
		link: link,
		scope: {

		}
	};
);

Every property in this object will be available within the scope of the directive. Its value will be determined by the value here. If we use "-" then the value will be equal to the value of the property with the same name. Using "=" will tell the compiler that we expect to pass variables in the current scope - this will work like

ngBind:

scope: {
	exampleBindLeet: '='
}

You can also use anything as a property name and put the normalized (converted to camelCase) property name after - or =:

scope: {
	text: '=exampleBindLeet'
}

Choose the one that suits you best. Now we also have to change the link function to use

$scope instead of attr:

function link($scope, $elem, attrs) {
    var leetText = $scope.exampleBindLeet.replace(/[abegilostz]/gmi, function (letter) {
		return leet[letter.toLowerCase()];
	});

	$elem.text(leetText);
}

現(xiàn)在使用 ngInit 或創(chuàng)建一個(gè)控制器,并將 divexample-bind-leet 屬性的值更改為您使用的變量的名稱:

 <body ng-app="example" ng-init="textToConvert = 'This text will be converted to leet speak!'"> 
    <div example-bind-leet="textToConvert"></div> 
</body> 

第 4 步:檢測更改

但這仍然不是 ngBind 的工作原理。要查看我們添加一個(gè)輸入字段以在頁面加載后更改 textToConvert 的值:

<input ng-model="textToConvert">

現(xiàn)在,如果您打開頁面并嘗試更改輸入中的文本,您將看到我們的 div 中沒有任何變化。這是因?yàn)?link() 函數(shù)在編譯時(shí)每個(gè)指令都會調(diào)用一次,因此它無法在每次范圍內(nèi)發(fā)生更改時(shí)更改元素的內(nèi)容。

要改變這一點(diǎn),我們將使用 $scope.$watch() 方法。它接受兩個(gè)參數(shù):第一個(gè)是 Angular 表達(dá)式,每次修改范圍時(shí)都會對其進(jìn)行求值,第二個(gè)是回調(diào)函數(shù),當(dāng)表達(dá)式的值發(fā)生更改時(shí)將被調(diào)用。

首先,讓我們將 link() 函數(shù)中的代碼放入其中的本地函數(shù)中:

function link($scope, $elem, attrs) {
    function convertText() {
		var leetText = $scope.exampleBindLeet.replace(/[abegilostz]/gmi, function (letter) {
			return leet[letter.toLowerCase()];
		});

		$elem.text(leetText);
	}
}

現(xiàn)在,在該函數(shù)之后,我們將調(diào)用 $scope.$watch(),如下所示:

$scope.$watch('exampleBindLeet', convertLeet);

如果您現(xiàn)在打開頁面并更改輸入字段中的某些內(nèi)容,您將看到 div 的內(nèi)容也按預(yù)期發(fā)生了變化。

元素指令:進(jìn)度條

現(xiàn)在我們將編寫一個(gè)指令來為我們創(chuàng)建一個(gè)進(jìn)度條。為此,我們將使用一個(gè)新元素:<example-progress>。

第 1 步:樣式

為了讓我們的進(jìn)度條看起來像一個(gè)進(jìn)度條,我們必須使用一些 CSS。將此代碼放入文檔的 <head> 中的 <style> 元素中:

example-progress {
    display: block;
	width: 100%;
	position: relative;
	border: 1px solid black;
	height: 18px;
}

example-progress .progressBar {
	position: absolute;
	top: 0;
	left: 0;
	bottom: 0;
	background: green;
}

example-progress .progressValue {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	text-align: center;
}

正如你所看到的,它非?;?- 我們使用 position:relativeposition:absolute 的組合來定位綠色條和 <example-progress> 元素。

第 2 步:指令的屬性

與前一個(gè)相比,這個(gè)需要更多的選項(xiàng)??匆幌逻@段代碼(并將其插入到您的 <script> 標(biāo)記中):

module.directive('exampleProgress', function () {
    return {
		restrict: 'E',
		scope: {
			value: '=',
			max: '='
		},
		template: '',
		link: link
	};
});

正如您所看到的,我們?nèi)匀皇褂梅秶ㄟ@次有兩個(gè)屬性 - value 表示當(dāng)前值,max 表示最大值)和 link() 函數(shù),但有兩個(gè)新屬性:

  • restrict: 'E' - 這告訴編譯器查找元素而不是屬性??赡艿闹禐椋?/li>
    • 'A' - 僅匹配屬性名稱(這是默認(rèn)行為,因此如果您只想匹配屬性,則無需設(shè)置它)
    • 'E' - 僅匹配元素名稱
    • 'C' - 僅匹配類名
  • 您可以將它們組合起來,例如“AEC”將匹配屬性、元素和類名稱。
  • template: '' - 這允許我們更改元素的內(nèi)部 HTML(如果您想從單獨(dú)的文件加載 HTML,還有 templateUrl)

當(dāng)然,我們不會將模板留空。將此 HTML 放在那里:

<div class="progressBar"></div><div class="progressValue">{{ percentValue }}%</div>

如您所見,我們還可以在模板中使用 Angluar 表達(dá)式 - percentValue 將從指令的范圍中獲取。

第3步:鏈接函數(shù)

該函數(shù)與上一個(gè)指令中的函數(shù)類似。首先,創(chuàng)建一個(gè)將執(zhí)行指令邏輯的本地函數(shù) - 在本例中更新 percentValue 并設(shè)置 div.progressBar 的寬度:

function link($scope, $elem, attrs) {
    function updateProgress() {
		var percentValue = Math.round($scope.value / $scope.max * 100);
		$scope.percentValue = Math.min(Math.max(percentValue, 0), 100);
		$elem.children()[0].style.width = $scope.percentValue + '%';
	}
}

正如你所看到的,我們不能使用 .css() 來更改 div.progressBar 的寬度,因?yàn)?jqLit??e 不支持 .children( )。我們還需要使用 Math.min()Math.max() 將值保持在 0% 到 100% 之間 - 如果 precentValue 小于 0,則 Math.max() 將返回 0;如果 percentValue 大于 100,則 Math.min() 將返回 100。

現(xiàn)在不再是兩個(gè) $scope.$watch() 調(diào)用(我們必須注意 $scope.value 中的變化$scope.max) 讓我們使用 $scope.$watchCollection(),它類似,但適用于屬性集合:

$scope.$watchCollection('[value, max]', updateProgress);

請注意,我們傳遞的第一個(gè)參數(shù)看起來像數(shù)組,而不是 JavaScript 的數(shù)組。

要了解它是如何工作的,首先更改 ngInit 以初始化另外兩個(gè)變量:

<body ng-app="example" ng-init="textToConvert = 'This text will be converted to leet speak!'; progressValue = 20; progressMax = 100">

然后在我們之前使用的 div 下面添加 <example-progress> 元素:

<example-progress value="progressValue" max="progressMax"></example-progress>

<body> 現(xiàn)在應(yīng)該如下所示:

<body ng-app="example" ng-init="textToConvert = 'This text will be converted to leet speak!'; progressValue = 20; progressMax = 100"> 
    <div example-bind-leet="textToConvert"></div> 
    <example-progress value="progressValue" max="progressMax"></example-progress> 
</body> 

這就是結(jié)果:

第 4 步:使用 jQuery 添加動畫

如果您為 progressValueprogressMax 添加輸入,如下所示:

<input ng-model="progressValue"> 
<input ng-model="progressMax">

您會注意到,當(dāng)您更改任何值時(shí),寬度會立即發(fā)生變化。為了讓它看起來更好一點(diǎn),讓我們使用 jQuery 來制作它的動畫。將 jQuery 與 AngularJS 結(jié)合使用的好處是,當(dāng)您包含 jQuery 的 <script> 時(shí),Angular 會自動用它替換 jqLit??e,使 $elem 成為 jQuery 對象。

因此,讓我們首先將 jQuery 腳本添加到文檔的 <head> 中,位于 AngularJS 之前:

<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>

現(xiàn)在我們可以更改 updateProgress() 函數(shù)以使用 jQuery 的 .animate() 方法。更改此行:

$elem.children()[0].style.width = $scope.percentValue + '%'; 

對此:

$elem.children('.progressBar').stop(true, true).animate({ width: $scope.percentValue + '%' }); 

并且您應(yīng)該有一個(gè)精美的動畫進(jìn)度條。我們必須使用 .stop() 方法來停止并完成任何待處理的動畫,以防我們在動畫進(jìn)行過程中更改任何值(嘗試刪除它并快速更改輸入中的值以了解為什么需要它)。 p>

當(dāng)然,您應(yīng)該更改 CSS,并可能在應(yīng)用程序中使用其他一些緩動函數(shù)來匹配您的風(fēng)格。

結(jié)論

AngularJS 的指令對于任何 Web 開發(fā)人員來說都是一個(gè)強(qiáng)大的工具。您可以創(chuàng)建一組自己的指令來簡化和促進(jìn)您的開發(fā)過程。您可以創(chuàng)建的內(nèi)容僅受您的想象力限制,您幾乎可以將所有服務(wù)器端模板轉(zhuǎn)換為 AngularJS 指令。

有用鏈接

以下是 AngularJS 文檔的一些鏈接:

  • 開發(fā)者指南:指令
  • 綜合指令 API
  • jqLit??e(angular.element)API

The above is the detailed content of Enhance HTML with AngularJS directives. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to diagnose high CPU usage caused by WordPress How to diagnose high CPU usage caused by WordPress Jul 06, 2025 am 12:08 AM

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

How to minify JavaScript files in WordPress How to minify JavaScript files in WordPress Jul 07, 2025 am 01:11 AM

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

How to optimize WordPress without plugins How to optimize WordPress without plugins Jul 05, 2025 am 12:01 AM

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

How to use the Transients API for caching How to use the Transients API for caching Jul 05, 2025 am 12:05 AM

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

How to prevent comment spam programmatically How to prevent comment spam programmatically Jul 08, 2025 am 12:04 AM

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

How to enqueue assets for a Gutenberg block How to enqueue assets for a Gutenberg block Jul 09, 2025 am 12:14 AM

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

How to add custom fields to users How to add custom fields to users Jul 06, 2025 am 12:18 AM

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

How to optimize WordPress robots txt How to optimize WordPress robots txt Jul 13, 2025 am 12:37 AM

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.

See all articles