Table of Contents
Prepare
Step 1: HTML Template
Step 2: Create module
第 4 步:检测更改
元素指令:进度条
第 1 步:样式
第 2 步:指令的属性
第3步:链接函数
第 4 步:使用 jQuery 添加动画
结论
有用链接
Home CMS Tutorial WordPress Enhance HTML with AngularJS directives

Enhance HTML with AngularJS directives

Aug 27, 2023 am 08:01 AM

使用 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>
Copy after login

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>
Copy after login

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', []);
Copy after login

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>
Copy after login

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 () {
Copy after login

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
	};
});
Copy after login

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) {
Copy after login

$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);
}
Copy after login

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'
};
Copy after login

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>
Copy after login

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

		}
	};
);
Copy after login

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: '='
}
Copy after login

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

scope: {
	text: '=exampleBindLeet'
}
Copy after login

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);
}
Copy after login

现在使用 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> 
Copy after login

第 4 步:检测更改

但这仍然不是 ngBind 的工作原理。要查看我们添加一个输入字段以在页面加载后更改 textToConvert 的值:

<input ng-model="textToConvert">
Copy after login

现在,如果您打开页面并尝试更改输入中的文本,您将看到我们的 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);
	}
}
Copy after login

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

$scope.$watch('exampleBindLeet', convertLeet);
Copy after login

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

元素指令:进度条

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

第 1 步:样式

为了让我们的进度条看起来像一个进度条,我们必须使用一些 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;
}
Copy after login

正如你所看到的,它非常基本 - 我们使用 position:relativeposition:absolute 的组合来定位绿色条和 <example-progress> 元素。

第 2 步:指令的属性

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

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

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

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

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

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

如您所见,我们还可以在模板中使用 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 + '%';
	}
}
Copy after login

正如你所看到的,我们不能使用 .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);
Copy after login

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

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

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

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

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

<body> 现在应该如下所示:

<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> 
Copy after login

这就是结果:

第 4 步:使用 jQuery 添加动画

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

<input ng-model="progressValue"> 
<input ng-model="progressMax">
Copy after login

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

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

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

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

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

对此:

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

并且您应该有一个精美的动画进度条。我们必须使用 .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 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

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

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)

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

How to sort posts by post expiration date in WordPress How to sort posts by post expiration date in WordPress Apr 19, 2025 pm 11:48 PM

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

How to display query count and page loading time in WordPress How to display query count and page loading time in WordPress Apr 19, 2025 pm 11:51 PM

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

See all articles