0

I'm a newbie on angularjs so I have a question for you. In my "standard html template" I have some html for the shopping cart summary, this html is on all the pages (like a popup to manage the cart quickly). So I was thinking to use a shared contoller to handle the common html pieces, something like:

app.controller ('SharedCtrl', function ($ brooms, cartService) {
    ...
    $ scope.cart = myBagService.get(); // get items from local store
    $scope.removeCartItem = function(key){
        myBagService.remove(key){..}; //remove stored item
        myBagService.add(item){..}; //store item
        $scope.cart = myBag.get(); //update binding items
    }
    ...
}

Is this a correct way to accomplish this task? if yes, how I can call the above methods from other controllers ? for example on the product detail page I have to call the add method.

DevT
  • 1,411
  • 3
  • 16
  • 32

2 Answers2

1

There are many ways to do it. Hope this will help to find the right method.

http://fdietz.github.io/recipes-with-angular-js/controllers/sharing-code-between-controllers-using-services.html

Angularjs sharing methods between controllers

Also you can read this: https://docs.angularjs.org/guide/controller

Community
  • 1
  • 1
andrey
  • 1,867
  • 3
  • 21
  • 34
1

Yes you can easily share functions/common code by using angular services, but I think sharing the functions/common code is only half your problem, as you noted you need to share "common html pieces", thus why not use a directive:

(function () {
   'use strict';
    app.directive('shoppingCart', function () {
        return {
            restrict: 'E',
            controller: 'ShoppingCartController as vm',            
            template: function (element, attrs) {
            return '<div data-ng-click="vm.onViewShpooingCart()">Click here to view shopping cart</div>';
            }
        };
    });
})();

The controller to the shopping-cart directive:

(function () {
   'use strict';
       app.controller('ShoppingCartController', ['$scope', 'sharedService'], function ($scope, sharedService) {
           var self = this;
           self.onViewShpooingCart = function () {
           sharedService.fetchShppingCart();
         };
    });
})();

The shared service:

(function () {
   'use strict';
    app.services.factory('sharedService', [function () {
        var service = {
           fetchShppingCart: fetchShppingCart
        };

        return service;

        function fetchShppingCart() {
            //code to fetch shopping cart
        }
    }]);
})();

By doing this you don't end up repeating your cart html on each page, its all rendered via the directive, you can then use the directive like below:

<shopping-cart></shopping-cart>
Tjaart van der Walt
  • 5,149
  • 2
  • 30
  • 50