如何在AngularJS中计算数组项目
给定一个数组,任务是在AngularJS中获得一个数组变量的长度。为此,我们将使用.length()方法来获取一个数组变量的长度。
例子1:在这个例子中,数组的长度由警报框显示。
<!DOCTYPE HTML>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
</script>
<script>
var myApp = angular.module("app", []);
myApp.controller("controller", function (scope) {
scope.arr = ['GFG', 'Geek',
'Geeks', 'GeeksForGeeks'];
scope.length = '';
scope.getLen = function () {
scope.length =scope.arr.length;
alert("Array Length = " + $scope.length);
};
});
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p>
How to count array items in AngularJS
</p>
<div ng-app="app">
<div ng-controller="controller">
<p>Array = {{arr}}</p>
<button ng-click="getLen()">
Click To Get Length
</button>
</div>
</div>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
例子2:在这个例子中,长度显示在 <p>
元素。
<!DOCTYPE HTML>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
</script>
<script>
var myApp = angular.module("app", []);
myApp.controller("controller", function (scope) {
scope.arr = ['GFG', 'Geek',
'Geeks', 'GeeksForGeeks'];
scope.length = '';
scope.getLen = function () {
scope.length =scope.arr.length;
};
});
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p>
How to count array items in AngularJS
</p>
<div ng-app="app">
<div ng-controller="controller">
<p>Array = {{arr}}</p>
<button ng-click="getLen()">
Click To Get Length
</button>
<p>Length is = {{length}}</p>
</div>
</div>
</body>
</html>
输出: