Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Add and Delete with AngularJS

1.00/5 (1 vote)
14 Jul 2015CPOL1 min read 4.8K   28  
How to add and delete with AngularJS

See if this will help!

Check out the demo here.

Introduction

This is a small tip with precise information about the demo that we have created. This is to show you how to add and delete with AngularJS.

Using the Code

The code is really simple. We have three controllers in which we have shown communication between them. You may get the same requirement. So, this will help you to get that stuff done easily.

The main.js file has 1 module and 3 controllers.

JavaScript
var mainModule = angular.module("mainModule",[]);
mainModule.controller("gridCtrl",['$scope', function ($scope) {
    // body...
}]);
mainModule.controller("formCtrl",['$scope', function ($scope) {
    // body...
}]);
mainModule.controller("registerCtrl",['$scope', function ($scope) {
    // body...
}]);

Here is how we can call our module and controllers in the HTML file.

JavaScript
<body ng-app="mainModule">
<div ng-controller="registerCtrl">
  <div ng-controller="gridCtrl">
  </div>
  <div ng-controller="formCtrl">
  </div>
</div>
</body>

Now, we have taxReturns JSON array. It is in a controller named as gridCtrl (see code in main.js file in demo).

JavaScript
$scope.$parent.taxReturns = [
    {"taxAgency":"Bevan", "status":"Draft"},
    {"taxAgency":"Ruth", "status":"Complete"},
    {"taxAgency":"TAX Agent","status":"Approved"}
];

We are adding new elements to the collection using the add function below. Here, currentRequest is a scope variable, see the HTML file in demo to see how we have used it as a model. It is in controller named as formCtrl (see code in main.js file in demo).

JavaScript
$scope.add = function(request){
        $scope.currentRequest = request;
        $scope.$parent.taxReturns.push($scope.currentRequest);
        $scope.currentRequest = {};
    }

Also, we have a delete function to delete the element as per its $index. It is in gridCtrl controller.

JavaScript
$scope.delete = function($index){
    alert($index);
    $scope.taxReturns.splice($index, 1);
}

Points of Interest

AngularJS is powerful, really powerful. Lots of interesting things to learn and apply!

History

I will see the feedback on this tip and try to get time to add more articles. Cheers people!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)