search
HomeCMS TutorialWordPressEnhance HTML with AngularJS directives

使用 AngularJS 指令增强 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 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 :

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 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. </script>

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

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);
}

现在使用 ngInit 或创建一个控制器,并将 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 的工作原理。要查看我们添加一个输入字段以在页面加载后更改 textToConvert 的值:

<input ng-model="textToConvert">

现在,如果您打开页面并尝试更改输入中的文本,您将看到我们的 div 中没有任何变化。这是因为 link() 函数在编译时每个指令都会调用一次,因此它无法在每次范围内发生更改时更改元素的内容。

要改变这一点,我们将使用 $scope.$watch() 方法。它接受两个参数:第一个是 Angular 表达式,每次修改范围时都会对其进行求值,第二个是回调函数,当表达式的值发生更改时将被调用。

首先,让我们将 link() 函数中的代码放入其中的本地函数中:

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

		$elem.text(leetText);
	}
}

现在,在该函数之后,我们将调用 $scope.$watch(),如下所示:

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

如果您现在打开页面并更改输入字段中的某些内容,您将看到 div 的内容也按预期发生了变化。

元素指令:进度条

现在我们将编写一个指令来为我们创建一个进度条。为此,我们将使用一个新元素:<example-progress></example-progress>

第 1 步:样式

为了让我们的进度条看起来像一个进度条,我们必须使用一些 CSS。将此代码放入文档的 中的 <style></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></example-progress> 元素。

第 2 步:指令的属性

与前一个相比,这个需要更多的选项。看一下这段代码(并将其插入到您的 <script></script> 标记中):

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

正如您所看到的,我们仍然使用范围(这次有两个属性 - value 表示当前值,max 表示最大值)和 link() 函数,但有两个新属性:

  • restrict: 'E' - 这告诉编译器查找元素而不是属性。可能的值为:
    • 'A' - 仅匹配属性名称(这是默认行为,因此如果您只想匹配属性,则无需设置它)
    • 'E' - 仅匹配元素名称
    • 'C' - 仅匹配类名
  • 您可以将它们组合起来,例如“AEC”将匹配属性、元素和类名称。
  • template: '' - 这允许我们更改元素的内部 HTML(如果您想从单独的文件加载 HTML,还有 templateUrl)

当然,我们不会将模板留空。将此 HTML 放在那里:

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

如您所见,我们还可以在模板中使用 Angluar 表达式 - percentValue 将从指令的范围中获取。

第3步:链接函数

该函数与上一个指令中的函数类似。首先,创建一个将执行指令逻辑的本地函数 - 在本例中更新 percentValue 并设置 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 的宽度,因为 jqLit​​e 不支持 .children( )。我们还需要使用 Math.min()Math.max() 将值保持在 0% 到 100% 之间 - 如果 precentValue 小于 0,则 Math.max() 将返回 0;如果 percentValue 大于 100,则 Math.min() 将返回 100。

现在不再是两个 $scope.$watch() 调用(我们必须注意 $scope.value 中的变化$scope.max) 让我们使用 $scope.$watchCollection(),它类似,但适用于属性集合:

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

请注意,我们传递的第一个参数看起来像数组,而不是 JavaScript 的数组。

要了解它是如何工作的,首先更改 ngInit 以初始化另外两个变量:

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

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

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

现在应该如下所示:

<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> 

这就是结果:

第 4 步:使用 jQuery 添加动画

如果您为 progressValueprogressMax 添加输入,如下所示:

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

您会注意到,当您更改任何值时,宽度会立即发生变化。为了让它看起来更好一点,让我们使用 jQuery 来制作它的动画。将 jQuery 与 AngularJS 结合使用的好处是,当您包含 jQuery 的 <script></script> 时,Angular 会自动用它替换 jqLit​​e,使 $elem 成为 jQuery 对象。

因此,让我们首先将 jQuery 脚本添加到文档的 中,位于 AngularJS 之前:

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

现在我们可以更改 updateProgress() 函数以使用 jQuery 的 .animate() 方法。更改此行:

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

对此:

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

并且您应该有一个精美的动画进度条。我们必须使用 .stop() 方法来停止并完成任何待处理的动画,以防我们在动画进行过程中更改任何值(尝试删除它并快速更改输入中的值以了解为什么需要它)。 p>

当然,您应该更改 CSS,并可能在应用程序中使用其他一些缓动函数来匹配您的风格。

结论

AngularJS 的指令对于任何 Web 开发人员来说都是一个强大的工具。您可以创建一组自己的指令来简化和促进您的开发过程。您可以创建的内容仅受您的想象力限制,您几乎可以将所有服务器端模板转换为 AngularJS 指令。

有用链接

以下是 AngularJS 文档的一些链接:

  • 开发者指南:指令
  • 综合指令 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
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
How to add a comment box to WordPressHow to add a comment box to WordPressApr 20, 2025 pm 12:15 PM

Enable comments on your WordPress website to provide visitors with a platform to participate in discussions and share feedback. To do this, follow these steps: Enable Comments: In the dashboard, navigate to Settings > Discussions, and select the Allow Comments check box. Create a comment form: In the editor, click Add Block and search for the Comments block to add it to the content. Custom Comment Form: Customize comment blocks by setting titles, labels, placeholders, and button text. Save changes: Click Update to save the comment box and add it to the page or article.

How to copy sub-sites from wordpressHow to copy sub-sites from wordpressApr 20, 2025 pm 12:12 PM

How to copy WordPress subsites? Steps: Create a sub-site in the main site. Cloning the sub-site in the main site. Import the clone into the target location. Update the domain name (optional). Separate plugins and themes.

How to write a header of a wordpressHow to write a header of a wordpressApr 20, 2025 pm 12:09 PM

The steps to create a custom header in WordPress are as follows: Edit the theme file "header.php". Add your website name and description. Create a navigation menu. Add a search bar. Save changes and view your custom header.

How to display wordpress commentsHow to display wordpress commentsApr 20, 2025 pm 12:06 PM

Enable comments in WordPress website: 1. Log in to the admin panel, go to "Settings" - "Discussions", and check "Allow comments"; 2. Select a location to display comments; 3. Customize comments; 4. Manage comments, approve, reject or delete; 5. Use <?php comments_template(); ?> tags to display comments; 6. Enable nested comments; 7. Adjust comment shape; 8. Use plugins and verification codes to prevent spam comments; 9. Encourage users to use Gravatar avatar; 10. Create comments to refer to

How to upload source code for wordpressHow to upload source code for wordpressApr 20, 2025 pm 12:03 PM

You can install the FTP plug-in through WordPress, configure the FTP connection, and then upload the source code using the file manager. The steps include: installing the FTP plug-in, configuring the connection, browsing the upload location, uploading files, and checking that the upload is successful.

How to copy wordpress codeHow to copy wordpress codeApr 20, 2025 pm 12:00 PM

How to copy WordPress code? Copy from the admin interface: Log in to the WordPress website, navigate to the destination, select the code and press Ctrl C (Windows)/Command C (Mac) to copy the code. Copy from a file: Connect to the server using SSH or FTP, navigate to the theme or plug-in file, select the code and press Ctrl C (Windows)/Command C (Mac) to copy the code.

What to do if there is an error in wordpressWhat to do if there is an error in wordpressApr 20, 2025 am 11:57 AM

WordPress Error Resolution Guide: 500 Internal Server Error: Disable the plug-in or check the server error log. 404 Page not found: Check permalink and make sure the page link is correct. White Screen of Death: Increase the server PHP memory limit. Database connection error: Check the database server status and WordPress configuration. Other tips: enable debug mode, check error logs, and seek support. Prevent errors: regularly update WordPress, install only necessary plugins, regularly back up your website, and optimize website performance.

How to close comments with wordpressHow to close comments with wordpressApr 20, 2025 am 11:54 AM

How to turn off a comment in WordPress? Specific article or page: Uncheck Allow comments under Discussion in the editor. Whole website: Uncheck "Allow comments" in "Settings" -> "Discussion". Using plug-ins: Install plug-ins such as Disable Comments to disable comments. Edit the topic file: Remove the comment form by editing the comments.php file. Custom code: Use the add_filter() function to disable comments.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools