jAYANT YADAV jAYANT YADAV - 1 year ago 140
AngularJS Question

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 have gone through numerous tutorials, but don't know where am I going wrong.
My service code is like this:

app.service('shareData', function() {

var selected = ["plz", "print", "something"];

var putSet = function(set) {
selected = set;

var getSet = function() {
return selected;

return {
putSet: putSet,
getSet: getSet

I am able to reach
from my function defined like this:

setDisplay = function($scope, $mdDialog, shareData) {

console.log(shareData.getSet()); // this is working

$scope.selected = shareData.getSet();
$scope.hide = function() {
$scope.cancel = function() {
$scope.answer = function(answer) {

My controller is like this:

app.controller('topicController', ['$scope', '$http', '$mdDialog', 'shareData',
function ($scope, $http, $mdDialog, $mdToast, shareData) {

console.log(shareData.getSet()); // NOT WORKING


Answer Source

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', & 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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download