3

I have a shopping cart component in my app. It lives in a controller. The controller is instantiated in a partial which is loaded to the page on demand (icon in menu bar).

app.controller('CartCtrl', function($scope, $http, storage) {
    $scope.options = {
        freeShipmentFrom: 180,
        shipmentCosts: 6
        ...
    };

    $scope.init = (function(){ ... }());

    $scope.addItem = function(){ ... };
    ...
    // more methods
    ...
});

Now I have to provide functionality outside of this partial/controller, even if that is not loaded to the page. I use directives for that, so for example I have a directive for adding items and for displaying the number of items in cart.

<button add-to-cart="productId">Add to cart</button>

How would you structure/design this component concerning best practices? Adding the "add-to-cart"-logic to the directive? Define a service outside of the partial mentioned above and accessing it from the directive and the controller of the partial?

Looking forward to read your thoughts on that!

kernfrucht
  • 3,448
  • 3
  • 15
  • 10

3 Answers3

3

Best practices to add shopping cart logic between a directive and controller is to use a service and inject it into a controller and directive. Here is an example on how to access a service from both:

var module = angular.module('app', [])
.controller('CartCtrl', function($scope, cartService){
  $scope.cartName = "My Cart"; 
  $scope.productId = 123; 
  $scope.addItem = function(productId){
    cartService.addProductId(productId); 
  };
})         
.factory('cartService', function(){
  var products = []; 
  return {
    addProductId : function(productId){
      products.push(productId); 
    }
  };
})
.directive('addToCart', function(cartService){
  function link($scope, element, attrs){
    $scope.$watch('productId', function(value){
      if(value){
      cartService.addProductId(value);
      }
    });

Here is a link : http://jsbin.com/IKadoYAK/4/edit

1

Referring to the AngularJS documentation, state should be shared via services. http://docs.angularjs.org/guide/controller#using-controllers-correctly

Manipulating the state could be done in directives or controllers. There you have the choice, but I recommend that you only use directives if there is really DOM interaction required. If this is not the case use simply the controller for that.

The service handling the state has to be injected into the controller/directive then, when you load your Partial.

0

I have answered a similar question. This question has 2 parts. Please refer to the second part and you will have your answer!

Spring MVC or Rest Services with spring + AngularJS

Have fun with Angular!!

Community
  • 1
  • 1
Abilash
  • 6,089
  • 6
  • 25
  • 30
  • My question is more meant like "where to put the logic to access it from different areas in the app?" than about directory/file structure. – kernfrucht Dec 21 '13 at 15:25