-1

I want data received by the service to be transmitted to the controller but the controller does not receive the data.

Service:

angular.module('dataService', [])
    .constant('productCategoryUrl', ' /api/product/categories')
    .service('dataService', function ($rootScope, $http, $filter, $rootScope, productCategoryUrl) {

        var currentData = {};
        var productCategories = [];  

        return {
            setCurrentCategory: function (category, type) {
                $rootScope.$broadcast('set-category', currentData);
            },
       }
   })

Controller:

angular.module('jordans')
    .controller('productCategoryCtrl', function ($scope, $rootScope, dataService) {
         $scope.productCategories = [];             

         $rootScope.$on('set-category', function (e, args) {                   
                $scope.currentData.category = args.category;
                $scope.currentData.type = args.type;

                console.log('*******productcategory.currentdata = ' 
                  + JSON.stringify($scope.currentData))                    
            });
  }
koque
  • 1,830
  • 5
  • 28
  • 49
  • Are you making a call to `dataService.setCurrentCategory()`? i.e. does the event even get raised!? – Matthew Cawley Sep 12 '17 at 19:51
  • Um, I prematurely accepted Ved's answer. It was not the solution. To your question, seCurrentCategory() is called. – koque Sep 12 '17 at 20:32

1 Answers1

2

Why two instances of $rootScope added in service. Removing this should fix the issue

.service('dataService', function ($rootScope, $http, $filter, $rootScope, productCategoryUrl) {

Should be:

service('dataService', function ($http, $filter, $rootScope, productCategoryUrl) {

Question:

Why you are using $broadcast in service. You can directly create method in service and call it from controller.

Also You need to destroy $rootScope listerner: See this answer:

Working with $scope.$emit and $scope.$on

Ved
  • 11,837
  • 5
  • 42
  • 60
  • 1
    Your implementation need to be improved. Also You need to destroy the rootscope listener. – Ved Sep 12 '17 at 19:54
  • Actually, Ved, I was a bit premature in accepting your answer. That was not the problem. – koque Sep 12 '17 at 20:27
  • @koque so do you fixed the issue? – Ved Sep 13 '17 at 05:03
  • Yes, Ved, the problem was, at the time of the broadcast by the dataService, the productCategoryCtrl was not loaded so it wasn't receiving the broadcast. – koque Sep 13 '17 at 22:20