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 selected
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() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(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
}]);
You had extra
$mdToast
in yourtopicController
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 parametershareData
get nothing.