AngularJS。返回新的工厂实例

时间:2013-12-27 12:40:31

标签: angularjs

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

我期待拥有的是具有更新字段的对象。 如何返回我的单身人士的新实例?

2 个答案:

答案 0 :(得分:11)

你想要这样的东西吗?

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

答案 1 :(得分:3)

就像你在邮政服务中写的那样,Singletons和它通过服务共享数据的好方法。但是,如果要创建工厂/服务的新实例,则不能这样做,但我们可以在一个服务/工厂中创建对象列表,其中每个列表项表示不同的实例。类似的东西:

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

    var medicalCenterServices = [
        {ctrlName: 'MedicalCenterController',medicalCenterService: {/*....*/}},
        {ctrlName: 'AccountProfileController',medicalCenterService: {/*....*/}},
    ];

        //......
})