我是AngularJS的新手,因此遇到了这个问题。

我可以在所有注入(inject)了 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/

10-11 01:34