Fotis Papadamis
Fotis Papadamis

Reputation: 303

AngularJS sharing data stored in controller between different modules

I'm completely new to AngularJS (version 1.6.9) and I've been trying to figure this out for a couple days now.

So, what I've been trying to achieve is a cart website in which you pick what you wish to buy, you click on checkout and you get to the checkout page where you can see what's in your cart and the total price. The problem is that when the user clicks on checkout and the checkout page loads, the products they picked and the total price of them should be presented. I have all this information stored in my cart module's controller but the question is how I can access that information from my checkout module's controller. I have tried creating a service, store the information there and then inject it to checkout controller but I can't properly store the information from my controller to the service.

'use strict';

//define CART module
angular.module('cart', ['ngRoute'])
//configuration for CART module
.config(['$routeProvider', function($routeProvider){
  $routeProvider.when('/cart', {
    templateUrl: '/public/cart/cart.html',
    controller: 'cartCtrl as vm'
  });
}])
.controller('cartCtrl', function(){
  this.chocolate =[
    {
      pack: '3',
      price: 5,
      checkState: false
    },
    {
      pack: '5',
      price: 7,
      checkState: false
    },
    {
      pack: '10',
      price: 10,
      checkState: false
    }
  ]
  this.honey = [
    {
      pack: '3',
      price: 5,
      checkState: false
    },
    {
      pack: '5',
      price: 7,
      checkState: false
    },
    {
      pack: '10',
      price: 10,
      checkState: false
    }
  ]
  this.candy = [
    {
      pack: '3',
      price: 5,
      checkState: false
    },
    {
      pack: '5',
      price: 7,
      checkState: false
    },
    {
      pack: '10',
      price: 10,
      checkState: false
    }
  ]

  this.totalCost = 0;
  this.calculateTotal = function (checked, price) {
    if (checked) {
      this.totalCost += price;
    } else {
      this.totalCost -= price;
    }
  }

});

'use strict';

angular.module('checkout', ['ngRoute'])
.config(['$routeProvider', function($routeProvider){
  $routeProvider.when('/checkout', {
    templateUrl: 'public/checkout/checkout.html',
    controller: 'checkoutCtrl'
  });
}])
.controller('checkoutCtrl', ['$scope', function($scope){

}]);

Upvotes: 0

Views: 33

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222582

First of all you should not inject ngRoute in both the modules, just have it in the main module.

angular.module('checkout', ['ngRoute']) //remove ngRoute from here

Second, just inject the second module to the first one as a dependency, add checkout here

angular.module('cart', ['ngRoute','checkout'])

Upvotes: 1

Related Questions