Passing Data Between Controllers in Angular JS

We can share data between two or more controllers using service or factory.

Example:

First, I am creating a product service.

myApp.service('productService', function() {
 var product = [], addProduct, getProductList, removeProduct;
     addProduct = function(obj) {
        product.push(obj);
     };
     getProductList = function(){
        return product;
     };
     removeProduct = function(id {
        product.splice(id, 1);
     };
     return {
        addProduct: addProduct,
        removeProduct: removeProduct,
        getProductList: getProductList
     };
}); 

Service will inject as a Dependency injection into controllers.

 

Now i will show. How to share product service in two controllers.

 

In ListController, we can add or remove product to cart from product list:

myApp.controller('ListController', function($scope, productService) {
   $scope.addToCart = function(obj) {
      productService.addProduct(obj);
   };
   
   $scope.removeToCart = function(id) {
      productService.removeProduct(id);
   };
});


In CartController, here we can get all product which we added to cart and also we can remove product from cart:

myApp.controller('CartController', function($scope, productService) {
   $scope.productList = productService.getProductList();

   $scope.removeToCart = function(id){
      productService.removeProduct(id);
   };
});

In place of service we can also use factory.

 

 

6 thoughts on “Passing Data Between Controllers in Angular JS

  1. Pingback: Gregory Smith
  2. Pingback: срочный заем на карту
  3. Pingback: Shailesh Kumar
  4. Hi everybody, here every one is sharing such familiarity,
    therefore it’s fastidious to read this website, and I used to pay a quick visit this
    webpage daily.

  5. Thanks for finally writing about > Passing Data Between Controllers in Angular
    JS | NITISH KUMAR – Programming Discussion Blog < Loved it!

Comments are closed.