0

When I am calling AngularJs factory method to bind a list of months with static array then it is working fine. But when I am using MVC Controller to return same data then $scope.months not binding list.

While the XHR response has the same data. I don't know what is the issue.

Following is code snippet :

HomeController.css

[HttpGet]
public ActionResult GetAllMonths()
{
    List<Month> monthList = new JsonRepository<Month>().GetAll();
    var output =  Json(monthList, JsonRequestBehavior.AllowGet);
    return output;
}

AngularJs Factory

(function () {
    'use strict'

    var app = angular.module("CommonFactory", []);

    app.factory("DataFactory", ["$http",DataFactory]);

    /*DI For Factory*/
    //DataFactory.$inject = ["$http"];



    //Factories callBack functions

    function DataFactory($http) {
        return {
            getMonths: function () {
                return $http({
                    method: 'GET',
                    url: '/Home/GetAllMonths'
                }).then(function(response){
                       return response.data;
                });
            }
        }
    }

})();

AngularJs Controller

//Modules With Controllers
var app = angular.module("PublicModule", [])
                 .controller("HomeController", homeController);


//Dependency Injection
homeController.$inject = ["$scope","$http", "DataFactory", "DataService"];


//Functions
function homeController($scope,$http, DataFactory,DataServic) {
    $scope.headingText = "Home";

    $scope.months = DataFactory.getMonths();
}

enter image description here

georgeawg
  • 48,608
  • 13
  • 72
  • 95

1 Answers1

1

Extract the data from the promise with its .then method:

//Functions
function homeController($scope,$http, DataFactory,DataService) {
    $scope.headingText = "Home";

    DataFactory.getMonths().then(function(data) {
        $scope.months = data;
    });
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • Thanks georgeawg! It's working good. But how to move this logic into getMonth() function of factory js – Praveen Kumar Mar 03 '19 at 19:20
  • I/O in JavaScript is non-blocking. That means that the code does not wait for the data to come back from the server. Instead the success/rejection function is held by the $q service and executed at a later time. For more infromation see [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – georgeawg Mar 03 '19 at 19:30