【发布时间】:2014-01-25 18:10:44
【问题描述】:
我正在构建一个具有顶级控制器和二级控制器的 Angular 应用程序。将有 n 个二级控制器,但我想将全局级函数放在某个地方。我在服务中这样做。
我开始创建一个返回 api 的单一服务,实际上,它包含许多函数(如下)。该服务返回一个具有两个属性分支的对象,每个属性分支都包含一组函数。我如何从另一个调用其中一个?
globalModule.factory('global', function($http) {
var squares = MyApp.squares; // this is the *only* link from Global namespace to this app
return {
squareMgr: {
getSquaresEarned: function() {
return squares.earned;
},
getSquaresPlaced: function() {
return squares.placed;
},
setThisSquareEarned: function(value) {
squares.earned.push(value);
},
setThisSquarePlaced: function(value) {
squares.placed.push(value);
}
},
missionMgr: {
missionInfo: {},
setMissionInfo: function(missionInfo) {
this.missionInfo = missionInfo
},
complete: function(missionData) {
log('complete called on video at ' + new Date());
missionData.complete = true;
log(angular.toJson(missionData));
$http({
url: '/show/completeMission',
method: "POST",
data: missionData
})
.then(function(response) {
if (response.data.success === true) {
log('completeMission success');
// increment squares earned counter
this.squareMgr.setThisSquareEarned(missionData.id);
// above is an attempt to run a function contained in this
// same service in a different parent property branch.
// how *should* I do this?
}
});
}
}
}
});
【问题讨论】:
-
我会尝试在
return语句之前创建squareMgr对象,然后在返回的对象中引用它。 -
如果它们本质上是两个服务,为什么不明确说明并创建两个服务呢?然后可以将一个注入另一个。
标签: angularjs angularjs-service