Skip to content Skip to sidebar Skip to footer

Angular: Not Able To Access Variables In Controller Using Service

I am trying to share a variable between a controller and a function. But i get an error from the controller, saying this: TypeError: Cannot read property 'getSet' of undefined I

Solution 1:

You had extra $mdToast in your topicController controller's factory function, you need to remove it.

The reason behind it was not working is, currently you had 4 dependency mentioned in array like ['$scope', '$http', '$mdDialog', 'shareData', function & then you are using its instance inside the function next to DI array. Inside that function you had actually 5 dependencies where $mdToast extra. So behind the scene what happening is $scope of function hold an value of '$scope' DI array likewise you go right to left. But when it comes to $mdToast(in controller function) it was holding a value of 'shareData'(of DI array) & then the next parameter shareData get nothing.

app.controller('topicController', ['$scope', '$http', '$mdDialog', 'shareData', 
      function ($scope, $http, $mdDialog, shareData) { //<--removed $mdToast
    console.log(shareData.getSet());
  }
]);

NOTE: You are using DI inline array annotation, so the sequence in which dependency are injected in array, in same sequence you should inject then in underlying factory function.

Post a Comment for "Angular: Not Able To Access Variables In Controller Using Service"