Home >Web Front-end >JS Tutorial >How to Share Data Between Controllers in AngularJS Using a Service?

How to Share Data Between Controllers in AngularJS Using a Service?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 12:58:16340browse

How to Share Data Between Controllers in AngularJS Using a Service?

Inter-Controller Data Transfer in AngularJS

In the realm of AngularJS, the need to exchange data between controllers is paramount for building sophisticated applications. Let's explore how to achieve this using a service.

In your scenario, where you want to add selected products to a shopping cart, you can leverage a service as the intermediary.

Creating the ProductService Factory

Initialize a service factory using AngularJS's factory function:

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

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

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

  return {
    addProduct: addProduct,
    getProducts: getProducts
  };
});

Injecting the Service into Controllers

Include the productService in both the ProductController and the CartController:

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

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

Now, when you click on a product in your ProductController, call the addProduct function of the productService to populate the productList. The CartController will always have access to the latest productList stored in the service.

The above is the detailed content of How to Share Data Between Controllers in AngularJS Using a Service?. 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