Angular ngRepeat 按索引跟踪
本文帮助你了解 $index
的 ngRepeat
跟踪,并在你的 Angular 应用程序中使用它。
在 AngularJS 中按 $index
跟踪
Angular 是一个具有许多内置功能的现代 JavaScript 框架。AngularJS 提供双向数据绑定,这意味着对模型所做的任何更改都会反映在视图中,反之亦然。
它还提供 ngRepeat
,它为数组或对象中的每个项目重复 DOM 元素。 $index
的 ngRepeat
轨道允许你使用它们的索引号指定应该重复哪些项目。
ngRepeat
是一个可以添加到 Angular 应用程序的 HTML 模板中的指令。它用于创建列表,并且可以将表达式作为参数。
ngRepeat
表达式有两个参数:一个变量名和这个变量名的值。
然后迭代这些变量,每次迭代都被一一分配给变量。问题是 ngRepeat
不会为最近显示的对象重建 DOM 组件。
我们使用 $index
的轨道来克服这个问题。
$index
的 ngRepeat
轨道为列表中的每个项目提供唯一标识符。
当你想要访问列表中的特定项目或当你拥有一组对象并需要访问这些对象中的属性时,此标识符会很有帮助;这是非常有益的。
$index
指令的跟踪工作如下。
在 AngularJS 中通过 $index
使用 Track
本节通过示例说明如何在你的 Angular 应用程序中通过 $index
使用 Angular 跟踪。
使用以下命令创建一个新项目。
ng new angular-track-by-index
在 app 文件夹中添加以下 JavaScript 代码。
var app = angular.module('Adil',[]);
app.controller('Demo',["$scope",function($scope){
$scope.delft = [];
$scope.add = function () {
$scope.delft.push($scope.example );
}
}]);
我们在 JavaScript 代码中使用了 $scope
,那么 $scope
是什么?在 AngularJS 中,$scope
是一个包含应用程序数据和操作的内置对象。
你可以将属性添加到控制器函数中的 $scope
对象,并将值或函数应用于它们。
$scope
充当控制器和视图 (HTML) 之间的链接。它将信息从控制器发送到视图。
添加以下 HTML 代码。
<h3>Example of Angular track by index</h3>
<p>Write anything in the box and press enter, you will understand the concept of Angular track by index</p>
<div ng-app="Adil">
<div class="Demo" ng-controller="Demo">
<form action="
" ng-submit="add()">
<input type="text" ng-model="example" />
</form>
<p ng-repeat="list in delft track by $index">{{list}}</p>
</div>
</div>
在本文中,我们已经看到 $index
的 ngRepeat
轨道是 Angular 的基本功能之一,它允许开发人员遍历数组并为数组中的每个项目呈现相同的 HTML。
使用此指令,开发人员可以轻松地为任何 HTML 列表创建可重用的模板。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。