Reputation: 8663
I have an angular controller which have a number of variables decalred. I am trying to access these in my angular service:
app.controller("MyController", function($scope, myService) {
var pageIDs = {
'1': 'home',
'2': 'contact-us',
'3': 'products',
'4': 'complaints'
}
var doSomething = {
'home': function () {
$scope.Model($scope.MyData, {
Data: $scope.Data
});
},
// Contact-us function ////////
// Products functions ////////
// Complaints functions ////////
}
$scope.service = myService.getData;
}
app.factory('myService', function() {
return {
getData: function() {
var Hash = window.location.hash;
if (Hash) {
var WithoutHash = WithHash.substring(1);
if (doSomething [WithoutHash]) doSomething [WithoutHash]();
}
}
};
});
As you can see, within myService, i am trying to access the var doSomething that is defined within my controller.
Upvotes: 0
Views: 37
Reputation: 465
You can give the variable to the service:
$scope.service = myService.getData(doSomething);
and in your service:
app.factory('myService', function() {
return {
getData: function(doSomething) {
var Hash = window.location.hash;
if (Hash) {
var WithoutHash = WithHash.substring(1);
if (doSomething [WithoutHash]) doSomething [WithoutHash]();
}
}
};
});
Upvotes: 1
Reputation: 23231
put all the variable in $scope or any object and pass service method like this :
app.controller("MyController", function($scope, myService) {
$scope.pageIDs = {
'1': 'home',
'2': 'contact-us',
'3': 'products',
'4': 'complaints'
}
var doSomething = {
'home': function() {
$scope.Model($scope.MyData, {
Data: $scope.Data
});
},
// Contact-us function ////////
// Products functions ////////
// Complaints functions ////////
}
$scope.service = myService.getData;
myService.setData($scope);
}
app.factory('myService', function() {
var controllerVar = {};
return {
getData: function() {
var Hash = window.location.hash;
if (Hash) {
var WithoutHash = WithHash.substring(1);
if (doSomething[WithoutHash]) doSomething[WithoutHash]();
}
}
setData: function(obj) {
controllerVar = obj;
}
};
});
Upvotes: 1