CaptainMorgan
CaptainMorgan

Reputation: 1253

Setting up AngularJS factory to share data

I have an existing factory that retrieves data via a http get.

myApp.factory('ModelSpecFactory', ['$http', function ($http) {

    var ModelSpecFactory = {};

    ModelSpecFactory.GetModelSpec = function (modelId,modelSpecListId) {
        return $http({
            method: 'GET',
            url: '/model_spec/GetModelSpec',
            params: { modelId: modelId, modelSpecListId: modelSpecListId }
        });
    };

    return ModelSpecFactory;

}]);

What I want to do is to add a variable to the factory, and put the results of the http.get into that variable. I also want to be able to update the variable. How would I incorporate the following example below, into my existing factory, taking into consideration that I want to save my object returned from the http.get rather that the name data.

myApp.factory('Data', function () {

    var data = {
        FirstName: ''
    };

    return {
        getFirstName: function () {
            return data.FirstName;
        },
        setFirstName: function (firstName) {
            data.FirstName = firstName;
        }
    };
});

Upvotes: 0

Views: 35

Answers (1)

Adam Zerner
Adam Zerner

Reputation: 19248

The easiest way would be to use .success:

myApp.factory('Data', function () {

    var data = {
        FirstName: ''
    };

    return {
        GetModelSpec: function (modelId,modelSpecListId) {
            return $http({
                method: 'GET',
                url: '/model_spec/GetModelSpec',
                params: { modelId: modelId, modelSpecListId: modelSpecListId }
            })
            .success(function(responseData) {
                data.FirstName = responseData.FirstName;
             });
        },
        getFirstName: function () {
            return data.FirstName;
        },
        setFirstName: function (firstName) {
            data.FirstName = firstName;
        }
    };
});

If you need/want the .success in your controller, you could do something like this:

// in factory
...
getData: function() {
  return data;
}

// don't use .success for GetModelSpec here
...

// in controller
$scope.data = GetModelSpec.getData();
$scope.makeCall = function() {
  GetModelSpec.success(function(data) {
    angular.copy(data, $scope.data);
    // need to use angular.copy to keep data bindings in tact
  });
}

This binds $scope.data to that object in your factory. When you get the data from .success, it's used to update that scope object, which is really a reference to the object in your factory.

angular.copy is necessary because it actually copies the data from your callback into the object. $scope.data = data would assign $scope.data to that returned data object. It wouldn't overwrite the object in your factory.

Upvotes: 1

Related Questions