Home > CMS Tutorial > WordPress > body text

Enhance HTML with AngularJS directives

王林
Release: 2023-08-27 08:01:15
Original
707 people have browsed it

使用 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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template