Passing Data Between Controllers in AngularJS
Passing data between controllers in AngularJS is a common task, and there are a few different ways to do it. In this article, we'll discuss using a service to pass data from the ProductController to the CartController.
Service Implementation
To begin, we'll define a service called productService that will manage our product list. This service will contain two functions: addProduct and getProducts. addProduct will add a new product to the list, and getProducts will return the entire list.
app.factory('productService', function() { var productList = []; var addProduct = function(newObj) { productList.push(newObj); }; var getProducts = function(){ return productList; }; return { addProduct: addProduct, getProducts: getProducts }; });
Controller Implementation
Next, we'll inject the productService into both our ProductController and CartController.
In the ProductController, we'll define a function called callToAddToProductList that will add the selected product to the list managed by the productService.
app.controller('ProductController', function($scope, productService) { $scope.callToAddToProductList = function(currObj){ productService.addProduct(currObj); }; });
In the CartController, we'll use the getProducts function to retrieve the product list from the productService and assign it to the $scope.products variable.
app.controller('CartController', function($scope, productService) { $scope.products = productService.getProducts(); });
DOM Update
Since your product list in the CartController is hardcoded, you'll need to update the DOM manually when a new product is added. One way to do this is to use the $watch function to watch for changes to the $scope.products variable and update the DOM accordingly.
app.controller('CartController', function($scope, productService) { $scope.products = productService.getProducts(); $scope.$watch('products', function(newValue, oldValue) { // Update the DOM here based on the new value of products }, true); });
By using a service to manage the product list and communicate between the two controllers, you can easily pass data between them and update the DOM accordingly.
The above is the detailed content of How Can I Efficiently Pass Data Between AngularJS Controllers?. For more information, please follow other related articles on the PHP Chinese website!