0
我有一個角度控制器,其中有許多變量decalred。我想在我的角度服務來訪問這些:AngularJS - 在控制器中定義的服務中訪問var
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]();
}
}
};
});
正如你所看到的,爲myService中,我試圖來訪問我的控制器中定義的VAR DoSomething的。
我認爲你應該改變你的方法,服務/工廠沒有線索在哪裏注入,如果你注入'myService' t 10個控制器,每個控制器都會有'doSomething'?將服務視爲控制器的助手或可從控制器提取的功能的集合,並且可以獨立工作或作爲少數控制器的通用部分。希望這是有道理的 – maurycy 2014-09-03 10:31:03