1

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;
        });
    }
peta
  • 139
  • 3
  • 18

1 Answers1

4

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;
});
maurycy
  • 8,455
  • 1
  • 27
  • 44
  • thanks! dataFactory.getSpec() was missing specId. I updated my post with the correct code. But how do I handle errors? if the server doesn't respond when I am making the call for example. – peta Oct 03 '14 at 13:27
  • +1 @peta you can handle the errors in your controller, like this: dataFactory.getSpec().then(function(response) { $scope.formData = response.data; }, funtion(error){ console.log('s**t happened...')}); – Josep Oct 03 '14 at 13:42
  • 1
    @peta Sorry, there was a typo, like this: dataFactory.getSpec().then(function(response) { $scope.formData = response.data; }, function(error){ console.log('s**t happened...')}); Example: http://plnkr.co/edit/kULmGJeUjmUsURzakp4m?p=preview – Josep Oct 03 '14 at 13:50