0
Passing Data Between Controllers in Angular JS
JavaScript
Angular
AngularJS

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.

For interesting topics visit http://www.nitishkumarsingh.com/blog

Author

Notifications

?