我有一个计划对象,当我从API收到时,它具有以下结构:
schedule : {
id,
name,
day,
month,
year,
shifts : [
{
id,
user,
tasks : [...]
}
]
}
我创建了三个services
:Schedule
,Shift
和Task
。例如,我的Schedule
服务是
app.factory('Schedule', function()
{
return function() {
// my methods here such as:
this.save = function();
this.remove = function();
this.createShift = function();
this.registerShift = function(shift);
}
});
我希望这些服务扩展我从API收到的原始对象,以便我的schedule
成为:
schedule : {
id,
name,
day,
month,
year,
shifts,
this.save = function(),
this.remove = function(),
this.createShift = function(),
this.registerShift = function(shift)
}
现在,我能想到的唯一方法是
angular.extend(scope.schedule, new Schedule());
但是,如果我可以将schedule
传递给我的服务并将其分配回来并保留所有原始对象,那就更好了,例如:
scope.schedule = new Schedule(scope.schedule);
// And all the attributes such as name, id, day, month, year are also returned back
这可能吗?
答案 0 :(得分:0)
function Ctrl($scope,Shedule){
$scope.schedule = {
id,
name,
day,
month,
year,
shifts : [
{
id,
user,
tasks : []
}
]
};
// pass schedule object as a parameter
Shedule.processShedule.call($scope.schedule);
}
service:
app.service('Shedule',function()
{
this.processShedule=function(obj){
//you can access your parent object using self variable
var self=obj;
self.name="xyz";
self.year="2014";
}
}
答案 1 :(得分:0)
这可能不是最好的方法,但我最终使用了以下(使用下划线):
app.factory('Schedule', function()
{
return function(schedule) {
// This adds all the key => value pairs to 'this'
var self = this;
_.each(schedule, function(value, key)
{
self[key] = value;
});
this.save = function();
this.remove = function();
this.createShift = function();
this.registerShift = function(shift);
}
});
然后在我的指示中,我去了
scope.schedule = new Schedule(scope.schedule);