0

I'm trying a sample with angularJs where I'm trying to call a factory method and in the factory method, I'm doing an ajax callback to get result from database and in the success event of the ajax callback, I need to call a function in the controller to bind the result to the UI.

My Angular Code:

angular.module('myApp.controllers', [])
  .controller('TasksListCtrl', ['$scope', '$rootScope', '$routeParams', 'Task',
    function($scope, $rootScope, $routeParams, Task) {
      debugger;

      //factory call
      Task.query({
        MobileNumber: $routeParams.MobileNumber,
        ClientCode: $routeParams.ClientCode
      });

      $rootScope.UserMobileNumber = $routeParams.MobileNumber;

      $scope.BindTasksList = function(resultData) {
        debugger;
        $scope.Tasks = resultData;
        $scope.$apply();
      }

    }
  ]);

My Angular Factory Code:

'use strict';

(function() {

  function GetTasks(MobileNumber, ClientCode) {
    debugger;
    $.ajax({
      url: '/api/TasksAPI/GetTasksList',
      type: 'GET',
      datatype: 'json',
      data: {
        'MobileNumber': MobileNumber,
        'ClientCode': ClientCode
      },
      success: function(response) {
        debugger;
        $scope.BindTasksList(response);
      },
      error: function(xhr) {}
    });
  };

  angular.module('myApp.DbScripts', [])
    .factory('Task', [
      function() {
        return {
          query: function(data) {
            debugger;
            GetTasks(data.MobileNumber, data.ClientCode);
          }
        }
      }
    ]);
}());

My app.js Code:

'use strict';

angular.module('myApp', [
  'ngTouch',
  'ngRoute',
  'ngAnimate',
  'myApp.controllers',
  'myApp.DbScripts'
]).
config(['$routeProvider',
  function($routeProvider) {
    debugger;
    $routeProvider.when('/tasks/:MobileNumber/:ClientCode', {
      templateUrl: 'partials/tasks-list.html',
      controller: 'TasksListCtrl'
    });
    $routeProvider.when('/tasks/:taskId', {
      templateUrl: 'partials/task-details.html',
      controller: 'TaskDetailCtrl'
    });
    $routeProvider.when('/tasks/:taskId/status', {
      templateUrl: 'partials/task-completion-details.html',
      controller: 'TaskCompletionDetailCtrl'
    });
    $routeProvider.when('/tasks/:taskId/route', {
      templateUrl: 'partials/route-details.html',
      controller: 'RouteDetailCtrl'
    });
    $routeProvider.otherwise({
      redirectTo: '/tasks'
    });
  }
]);

But, I'm unable to call the function in controller. I've also tried it with angular.element(document.getElementById('TasksListCtrl')).scope().BindTasksList(response). But even that's not working.

Can anyone please point out the mistake I'm doing?
How to send the $scope of the controller to the factory?

3
  • 1
    myApp.DbScripts is a different module and needs to be added to the controller module: angular.module('myApp.controllers', ['myApp.DbScripts']) Commented Dec 2, 2015 at 6:35
  • I'm getting this error : Uncaught Error: [$injector:modulerr] Commented Dec 2, 2015 at 6:43
  • 1
    Shouldn't the controller be the one calling the factory methods? Not the other way around? Commented Dec 2, 2015 at 6:48

1 Answer 1

1

You can do this by leveraging the $http promises, in you factory, return the promise instead as follows

'use strict';

(function() {

  function GetTasks(MobileNumber, ClientCode) {

  };

  angular.module('myApp.DbScripts', [])
    .factory('Task', [
      function($http) {
        return {
          query: function(data) {
           return $http({
                   url: '/api/TasksAPI/GetTasksList',
                   method: 'GET',
                   params: {
                            'MobileNumber': data.MobileNumber,
                            'ClientCode': data.ClientCode
                           }
                }).then(function(result) {
                   return result;
                });
          }
        }
      }
    ]);
}());

Then in your controller you can access the $http response object that is returned:

      //factory call
      Task.query({
        MobileNumber: $routeParams.MobileNumber,
        ClientCode: $routeParams.ClientCode
      }).then(function(resp) {
           // access $http resp here and attach to $scope.Tasks
      });

If you can, I would advocate using $q along $http as well, so that you do not need to parse through the http response and get a nice little response data object back

plnk

Sign up to request clarification or add additional context in comments.

8 Comments

Hello @Kashyap : Thanks for the reply. Actually, now I'm getting $http is not a function error in factory.
can you make sure you have injected in the factory function?
angular.module('myApp.DbScripts', []) .factory('Task', [ function ($http) { return { query: function (data) { } } }]);
try angular.module('myApp.DbScripts', []) .factory('Task', ['$http', function ($http) { return { query: function (data) { } } }]);
Your Plunker has .factory('Task', [ '$http',. Also .then(function(result) {return result;}) is redundant and not needed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.