peta
peta

Reputation: 139

Get data from Factory

What I am trying to achieve:

  1. Pass the parameter specId from the controller to the factory
  2. In the factory: perform a $http.get to get JSON data
  3. Return the JSON data to the controller
  4. Displaying the information by assigning it to the $scope.formData

I tried many different ways but it only returns undefined. Before I created the factory I performed the $http.get directly in the controller without any issues, but now I am trying to structure the app in a better way.

Factory:

app.factory("dataFactory", function($http) {
    var factory = {};

    factory.getSpec = function(specId) {
        return $http.get('getSpec.aspx?specId=' + specId)
    };

    return factory;
});

Controller

app.controller('EditSpecController', function ($scope, $stateParams, $http, dataFactory) {
    $scope.specId = $stateParams.specId;
    $scope.formData = [];

    if($scope.specId) { //If EDIT MODE
        dataFactory.getSpec($scope.specId).then(function(response) {
            $scope.formData = response.data;
            $scope.use_unit = response.data.use_unit;
        });
    }

Upvotes: 1

Views: 2273

Answers (1)

maurycy
maurycy

Reputation: 8465

As you noticed $http returns promise already, so you should do something more like this

factory.getSpec = function(specId) {
    return $http.get('getSpec.aspx' + specId)
};

and then in controller

dataFactory.getSpec().then(function(response) {
  $scope.formData = response.data;
});

Upvotes: 4

Related Questions