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.
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 }; });
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!