Enhance HTML with AngularJS directives
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.
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
Usemodule.directive() method to declare instructions:
module.directive('exampleBindLeet', function () {
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 jqLitee, 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).
var leetText = attrs.exampleBindLeet.replace(/[abegilostz]/gmi, function (letter) { return leet[letter.toLowerCase()]; }); $elem.text(leetText); }
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' };
<script> tag. As you can see, this is the most basic leet converter since it only replaces ten characters.
text() method to put into the inner text of the element matched by this directive.
<body> of your document:
<div example-bind-leet="This text will be converted to leet speak!"></div>
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 theexample-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.
module.directive('exampleBindLeet', function () { ... return { link: link, scope: { } }; );
ngBind:
scope: { exampleBindLeet: '=' }
scope: { text: '=exampleBindLeet' }
$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 或创建一个控制器,并将 div
的 example-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>
。
第 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; }
正如你所看到的,它非常基本 - 我们使用 position:relative
和 position:absolute
的组合来定位绿色条和 <example-progress>
元素。
第 2 步:指令的属性
与前一个相比,这个需要更多的选项。看一下这段代码(并将其插入到您的 <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 的宽度,因为 jqLite 不支持 .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 value="progressValue" max="progressMax"></example-progress>
<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>
这就是结果:
第 4 步:使用 jQuery 添加动画
如果您为 progressValue
和 progressMax
添加输入,如下所示:
<input ng-model="progressValue"> <input ng-model="progressMax">
您会注意到,当您更改任何值时,宽度会立即发生变化。为了让它看起来更好一点,让我们使用 jQuery 来制作它的动画。将 jQuery 与 AngularJS 结合使用的好处是,当您包含 jQuery 的 <script>
时,Angular 会自动用它替换 jqLite,使 $elem
成为 jQuery 对象。
因此,让我们首先将 jQuery 脚本添加到文档的 <head>
中,位于 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
- jqLite(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!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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)

Hot Topics

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

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

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.

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

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.

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

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