我是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(); }; }