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!