Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS. Return new factory instance

Tags:

angularjs

I'm a newbie in AngularJS and have faced the issue.

Can I reinject my factory singleton object across all controllers, where it's been injected?

For example:

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

In MedicalCenterController I get singleton object with medical center when application starts:

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

But later I try to edit medical center fields (name, address, etc..) in AccountProfileController

function AccountProfileController($scope, medicalCenterService) {

    $scope.currentMedCenter = medicalCenterService.currentMedCenter;

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

And what I'm expecting to have is the object with updated fields. How to return a new instance of my singleton?

like image 807
Artyom Pranovich Avatar asked Dec 27 '13 12:12

Artyom Pranovich


1 Answers

Do you want something like this?

.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();
    };
}
like image 73
kfis Avatar answered Sep 26 '22 23:09

kfis