【问题标题】:View Binding Issue Using Data Returned From Factory使用从工厂返回的数据查看绑定问题
【发布时间】:2019-03-03 18:44:14
【问题描述】:

当我调用 AngularJs 工厂方法将月份列表与静态数组绑定时,它工作正常。但是当我使用 MVC 控制器返回相同的数据时,$scope.months 不是绑定列表。

虽然 XHR 响应具有相同的数据。我不知道是什么问题。

下面是代码sn-p:

HomeController.css

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

AngularJs 工厂

(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 控制器

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

【问题讨论】:

    标签: angularjs model-view-controller


    【解决方案1】:

    使用 .then 方法从 Promise 中提取数据:

    //Functions
    function homeController($scope,$http, DataFactory,DataService) {
        $scope.headingText = "Home";
    
        DataFactory.getMonths().then(function(data) {
            $scope.months = data;
        });
    }
    

    【讨论】:

    • 谢谢georgeawg!它运作良好。但是如何将此逻辑移动到工厂js的getMonth()函数中
    • JavaScript 中的 I/O 是非阻塞的。这意味着代码不会等待数据从服务器返回。相反,成功/拒绝函数由 $q 服务持有并在稍后执行。有关更多信息,请参阅How do I return the response from an asynchronous call?
    猜你喜欢
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2013-07-07
    • 2016-07-20
    相关资源
    最近更新 更多