-1

I got this angular factory:

var productApp = angular.module('productApp', ['ngRoute', 'LocalStorageModule', 'angularSlideables', 'ui.bootstrap']);

productApp.factory('productFactory', function($http, localStorageService, $q) {
    var factory = {};

    factory.getProductById = function(prod_id) {        
        if(prod_id !== '') {
            $http({
                url: 'rest/message/getProductById/' + prod_id,
                method: 'GET'
            }).success(function(data, status) {
                return data;
            }).error(function(data, status){
                // do nothing
            });
        }else {
            alert("There was an error while passing the ID. Please refresh the page and try again");
        }       
    }

    return factory;
});

Injecting the factory in a controller and calling to the "getProductById" function:

productApp.controller('ModalInstanceCtrl', function ($scope, $modalInstance, productFactory, prodId) {  
  console.log("this is the prod id " + prodId);
  // search product in the database
  $scope.prod = productFactory.getProductById(prodId);
  console.log($scope.prod);
  $scope.ok = function () {
      console.log($scope.prodData);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

Now, don't know what's wrong with it... the function RETURNS the data because i did a console.log(data) and saw all the response, but in the controller if i inspect the $scope.prod, it's undefined. It's not returning the data back from the function.

(Just in case you guys ask, the "prodId" in the controller parameter is fine, and retrieving that from another controller)

How can i solve this? :(

Thanks in advance.

user3078876
  • 157
  • 3
  • 16
  • your factory function doesn't return anything, which is why you get `undefined`...return the request and use `then` in controller to set scope property. The `return` within success doesn't do anything – charlietfl Dec 11 '13 at 00:30
  • @charlietfl can you answer below with a little example and then i can tick you as correct answer if this works ? thanks ! :) – user3078876 Dec 11 '13 at 00:42

2 Answers2

1

Here's what I do. I'm using $resournce instead of $http, but it should be enough to get you going. You may even want to use the $resource since it has the built in fns.

My factory:

.factory('WorkOrder', function($resource){

    // $resource Usage: $resource(url[, paramDefaults][, actions]);
    return $resource('/controller/get/:id.json', {}, {
        /*
         * By default, the following actions are returned; modify or add as needed
         * { 'get':    {method:'GET'},
         *   'save':   {method:'POST'},
         *   'query':  {method:'GET', isArray:true},
         *   'delete': {method:'DELETE'} };
         */
    });

})

My controller:

    // get the work order data using the work order id from the tag attribute
var getWO = function() {

    WorkOrder.get({woId:$attrs.id},

        // success callback
        function(response) {
            // Assign the work order data to the scope
            $scope.WorkOrder            = response.WorkOrder;
        },

        // fail callback
        function(response) {
            // whatever...
        }
    );
};
getWO();

I put my success and fail fns in my controller because that's where I most likely know how I want to respond to success or failed calls. I also assign the function to a variable and then call it right after in case I want to include the fn call inside a $timeout or call it elsewhere.

Hope this answers your question.

Darryl
  • 1,451
  • 1
  • 12
  • 19
1

The pattern I have used to solve this problem is to pass in the success & error callback functions to the factory... like this:

var productApp = angular.module('productApp', ['ngRoute', 'LocalStorageModule', 'angularSlideables', 'ui.bootstrap']);

productApp.factory('productFactory', function($http, localStorageService, $q) {
    var factory = {};

    factory.getProductById = function(prod_id, successCallback, errorCallback) {        
        if(prod_id !== '') {
            $http({
                url: 'rest/message/getProductById/' + prod_id,
                method: 'GET'
            })
            .success(successCallback)
            .error(errroCallback);
        } else {
            alert("There was an error while passing the ID. Please refresh the page and try again");
        }       
    }

    return factory;
});

and then:

productApp.controller('ModalInstanceCtrl', function ($scope, $modalInstance, productFactory, prodId) {  
  console.log("this is the prod id " + prodId);
  // search product in the database
  productFactory.getProductById(prodId, function successCallback(data) {
         $scope.prod = data;
      }, function errorCallback(data, status) {
         alert("An error occurred retrieving product. Please refresh the page & try again.");
      });
  console.log($scope.prod);

  $scope.ok = function () {
      console.log($scope.prodData);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

By doing it this way instead, you have access to the scope in the controller & can do whatever you need to with the returned data.

Matt Welch
  • 670
  • 4
  • 11