How to push item to 0 index or first of $scope object in AngularJS?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Now in this blog i will show how to push item to 0 index or first of $scope object in AngularJs. When we are working on angular JS and also we wanted to add item on top of array, here i mean that is we need to add 0 index of $scope array then we can do this. Now in this following example we can see how we can do this. If we want to push first then we need to use splice() instend of push().

Example:

<html>
<head>
	<title>Angular JS</title>
	<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
	<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
	<script>
		app.controller("myCtrl", function($scope) {
		    $scope.arrayMy = [4,3,2,1];
			$scope.addIndex = function () {
		        var t = $scope.arrayMy.length + 1;
		        $scope.arrayMy.splice(0, 0, t);
		    };
		});
	</script>
</head>
<body ng-app="myApp">
	<div ng-controller="myCtrl">
	  	<ul>
	  		<li ng-repeat="a in arrayMy">{{ a }}</li>
	  	</ul>
	  	<input type="button" ng-click="addIndex()" value="Add Index" />
	</div>
</body>
</html>

Read Also : How to copy one table data into another table in Mysql Query?

Thanks for read. I hope it help you. For more you can follow us onĀ facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →