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
Release: 2024-12-24 14:32:10
Original
242 people have browsed it

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
  };

});
Copy after login

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();
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template