Home >Web Front-end >JS Tutorial >How to Effectively Share Data Between AngularJS Controllers?

How to Effectively Share Data Between AngularJS Controllers?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 14:32:10283browse

How to Effectively Share Data Between AngularJS Controllers?

How to Share Data between Controllers in Angular JS?

To share data between controllers in AngularJS, using a service is recommended. Here's how you can implement this solution:

Create a Product Service:

app.factory('productService', function() {
  var productList = [];

  var addProduct = function(newObj) {
      productList.push(newObj);
  };

  var getProducts = function(){
      return productList;
  };

  return {
    addProduct: addProduct,
    getProducts: getProducts
  };

});

Inject the Service into Controllers:

app.controller('ProductController', function($scope, productService) {
    $scope.callToAddToProductList = function(currObj){
        productService.addProduct(currObj);
    };
});

app.controller('CartController', function($scope, productService) {
    $scope.products = productService.getProducts();
});

With these steps, data can be shared between the ProductController and CartController through the productService. The ProductController adds selected products to the service, and the CartController retrieves them to update the product list in the view.

The above is the detailed content of How to Effectively Share Data Between AngularJS Controllers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn