Thursday 8 January 2015

Adding and removing from list using push and splice in AngularJS.



angularjs
Since the last time I tried to manipulate ng-repeat and suddenly came up with how about making it more dynamic such as add or remove from the list. So I have added one input box and a button to add to the list and correspondingly added one remove link beside every list element to remove from the list. I felt so excited when it's worked out, so I thought of sharing the code with you..


//---------------------------------------------------------------------------------------------------------------------------

<!DOCTYPE html>
<!-- Declaringf directives -->
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>Add remove elementsr</title>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
myApp = angular.module('myApp',[]);
//Creating controller
myApp.controller('NameCtrl',function($scope) {
    $scope.names=['Larry Page','Mark Zukerberg','Steve Jobs','Bill Gates'];
 //Data added
//addNames function to add new data into the list
$scope.addNames = function () {
    $scope.names.push($scope.addedName);
    //addedNames input box is cleaned up after name have been added
    $scope.addedName = '';
}
//Remove name function to remove elements from the list.
$scope.removeNames = function (name) {
    $scope.names.splice($scope.names.indexOf(name),1);

}

});

</script>
</head>
<!--Controller set to body scope -->
<body ng-controller='NameCtrl'>
<ul id="nav" role="navigation">
<!-- ng-repeat to repeat list for number of elements  and ng-click set to href link to remove elements-->
<li ng-repeat="name in names">{{name}}  <a href ="" ng-click="removeNames(name)">Remove </a></li>
</ul>
<!--ng-model set to input box -->
<input type=text ng-model="addedName" />
<!--function addNames will be called on form submit ng-submit is used which prevents reloading of the page -->
<form ng-submit="addNames()">
<input type="submit" value="Add" />
</forms>
</body>
</html>

Here is the demo apps just look into this,
Add remove elementsr

No comments: