在本教程中,我们将介绍如何在Angular JS中将ng-repeat指令与Json一起使用,例如:
ng-repeat
的 ng-repeat 指令对集合中的每个项目实例化一次模板。每个模板实例都有其自己的作用域,其中给定的循环变量设置为当前集合项,$ index设置为项索引或键。
换句话说,它读取json数据,并立即通过一个html标签显示所有数据。它的属性是执行循环,直到json对象中的数据结束为止。
AngularJS(CDN链接)
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
ng-repeat与表格
在这个概念中,我们将看到 ng-repeat 通过表在angularJS中进行指令。表数据通过json对象加载。由于它执行循环,因此减少了单个html标签的声明。
让我们看一个例子 ng-repeat 与表。
app.js
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
$scope.options = {
//JSON DATA
langs: [
{label: 'Name', value: 'geekstrick'},
{label: 'Status', value: 'Active'},
{label: 'Course', value: 'Programming'},
{label: 'Since', value: '2017'},
{label: 'Author', value: 'Rehmaanali'}
],
};
});
index.html
<html>
<script src= "//ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src= "./app.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="l in options.langs">
<td>{{ l.label }}</td>
<td>{{ l.value }}</td>
</tr>
</table>
</div>
</body>
</html>
Json包含第一个键值对。因此,关键在于 {{l.label}} 并打印其值。
带链接的ng-repeat
我们将看到 ng-repeat 通过Links在angularJS中使用指令。链接通过json对象加载。它还可以为该链接索引一个垂直名称。
让我们看一个例子 ng-repeat 与链接。
app.js
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
$scope.options = {
// JSON Data
langs: [
{label: 'GeeksTrick', link: 'http://www.geekstrick.com'},
{label: 'Google', link: '//www.google.com'},
{label: 'Facebook', link: '//www.facebook.com'},
{label: 'Instagram', link: '//www.instagram.com'},
{label: 'Twitter', link: '//www.twitter.com'}
],
};
});
index.html
<html>
<script src= "//ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<a ng-repeat="l in options.langs" href="{{ l.link }}">{{ l.label }}</a>
</div>
</body>
</html>
指令 ng-repeat 会将特定链接分类为特定名称。
ng-repeat图片
在这个概念中,我们将看到 ng-repeat 通过图像在angularJS中使用指令。图片源将通过json对象加载。
让我们看一个例子 ng-repeat 与图像。
app.js
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
$scope.options = {
// JSON Data
langs: [
{ link: '//s-media-cache-ak0.pinimg.com/originals/2d/fb/d3/2dfbd38983291d3d0e5c1cb0667406b5.jpg'},
{ link: '//s-media-cache-ak0.pinimg.com/originals/e3/48/19/e34819dd10cff77a959733c110cda901.jpg'},
{ link: 'http://www.pngmart.com/files/4/Cute-Cartoon-PNG-Picture.png'},
{ link: 'http://www.kidsworldfun.com/images/story-contest/2016-2/elephant-cartoon.png'},
],
};
});
index.html
<html>
<script src= "//ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<img ng-repeat="l in options.langs" src="{{ l.link }}"/>
</div>
</body>
</html>
指令 ng-repeat 将获取源并通过image标签显示图像。