AngularJs count array items


AngularJs count array items – You can get the array length using the length method. Here in this tutorial we are going to explain how you can get the length of array variable in angularjs. You can also use our online editor to edit and run the code online.


AngularJs count array items | Example

Let us go step by step to create the array length example –

JavaScript Part

JavaScript Part Contains the following part as below –

AngularJs count array items:

 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
 $scope.myArray = ['Car', 'Bus', 'Truck','Train'];
 $scope.length = '';
 $scope.getLength = function() {
     $scope.length = $scope.myArray.length;
	 alert("Array Length = "+$scope.length);
 };
});
</script>

Html Part

Html Part contains the following html as below –

AngularJs count array items in View:

<div ng-app="myApp">  
<div ng-controller="myController">  

        <button ng-click="getLength()">Click To Get Length</button>
 
 <p>Array = {{myArray}}</p>
 <p>Length = {{length}}</p>
</div> 
</div>

Complete Part

Now let us combine both html and JavaScript parts –

AngularJs count array items Example:

<!DOCTYPE html>
<html lang="en">
<head>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
 $scope.myArray = ['Car', 'Bus', 'Truck','Train'];
 $scope.length = '';
 $scope.getLength = function() {
     $scope.length = $scope.myArray.length;
	 alert("Array Length = "+$scope.length);
 };
});
</script>
</head>
<body>  
<div ng-app="myApp">  
<div ng-controller="myController">  

        <button ng-click="getLength()">Click To Get Length</button>
 
 <p>Array = {{myArray}}</p>
 <p>Length = {{length}}</p>
</div> 
</div>
</body>  
</html>      
                                

Try it »

If you run the above example it will produce output something like this –

AngularJs count array items


Advertisements

Add Comment

📖 Read More