gpt4 book ai didi

AngularJS。返回新的工厂实例

转载 作者:行者123 更新时间:2023-12-03 06:30:15 27 4
gpt4 key购买 nike

我是 AngularJS 的新手,也遇到过这个问题。

我可以在所有 Controller 中重新注入(inject)我的工厂单例对象吗?

例如:

.factory('medicalCenterService', function(MedicalCenterResource) {

var medicalCenterService = {};

medicalCenterService.currentMedCenter = MedicalCenterResource.get();

medicalCenterService.reloadMedCenter = function() {
medicalCenterService.currentMedCenter = MedicalCenterResource.get();

return medicalCenterService.currentMedCenter;
};

medicalCenterService.updateMedicalCenter = function(medicalCenter) {
MedicalCenterResource.updateMedicalCenter(medicalCenter);
medicalCenterService.currentMedCenter = medicalCenter;
};

return medicalCenterService;
})

在 MedicalCenterController 中,当应用程序启动时,我得到医疗中心的单例对象:

function MedicalCenterController($scope, medicalCenterService) {
$scope.currentMedCenter = medicalCenterService.currentMedCenter;
}

但后来我尝试在 AccountProfileController 中编辑医疗中心字段(名称、地址等)

function AccountProfileController($scope, medicalCenterService) {

$scope.currentMedCenter = medicalCenterService.currentMedCenter;

$scope.applyMedCenterChanges = function (currentMedCenter) {
medicalCenterService.updateMedicalCenter(currentMedCenter);
};
}

我期望得到的是具有更新字段的对象。如何返回我的单例的新实例?

最佳答案

你想要这样的东西吗?

.factory('MedicalCenter', function(MedicalCenterResource) {
var MedicalCenter = function () {
var center = MedicalCenterResource.get(),
update = function() {
MedicalCenterResource.updateMedicalCenter(center)
};
return {
center: center,
update: update
}
};
return MedicalCenter;

})

function MedicalCenterController($scope, MedicalCenter) {
center = new MedicalCenter();
$scope.currentMedCenter = center.center;
}
function AccountProfileController($scope, MedicalCenter) {
center = new MedicalCenter();
$scope.currentMedCenter = center.center;
$scope.applyMedCenterChanges = function () {
center.update();
};
}

关于AngularJS。返回新的工厂实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20800909/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com