View Binding Issue Using Data Returned From Factor

2020-05-01 10:09发布

问题:

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();
}

回答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;
    });
}