我是AngularJS的新手,因此遇到了这个问题。
我可以在所有注入了控制器的工厂中重新注入我的工厂单例对象吗?
例如:
.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(); }; }