我的模型绑定发生了什么?

时间:2017-12-01 23:12:26

标签: angularjs

我有一个小型的AngularJs应用程序,它使用$resource来使用RESTful Web服务。资源(salesOrderResource)返回我绑定到模型vm.rowData的五个对象。我将返回的资源写出到控制台,以显示我确实有数据:

proof of data returned from web service

但是,一旦在资源的query功能之外,vm.rowData突然未定义undefined message for vm.rowdata

我无法弄清楚为什么会这样。我希望有人可以了解这里发生的事情。

这是我的控制人员:



(function () {
    "use strict";

    angular
        .module("app")
        .controller("SalesOrderListCtrl", ["salesOrderResource", SalesOrderListCtrl]);

    function SalesOrderListCtrl(salesOrderResource) {
        var vm = this;            

        vm.columnDefs = [
            { headerName: "Sales Order#", field: "SalesOrderNumber" },
            { headerName: "Lot#", field: "LotNumber" },
            { headerName: "Qty", field: "Quantity" },
            { headerName: "Status", field: "Status" },
            { headerName: "Branch", field: "Branch" }
        ];

        salesOrderResource.query(function (data) {
            vm.rowData = data;
            console.log("In query function:");
            console.log(vm.rowData);
        })     

        console.log("Outside query function:");
        console.log(vm.rowData);

        vm.gridOptions = {

            // PROPERTIES - object properties, myRowData and myColDefs are created somewhere in your application
            rowData: vm.rowData,
            columnDefs: vm.columnDefs,

            // PROPERTIES - simple boolean / string / number properties
            enableColResize: true,
            rowHeight: 22,
            rowSelection: "single",

            // EVENTS - add event callback handlers
            onRowClicked: function (event) { console.log("a row was clicked"); },
            onColumnResized: function (event) { console.log("a column was resized"); },
            onGridReady: function (event) { console.log("the grid is now ready"); },

            // CALLBACKS
            isScrollLag: function () { return false; }
        }           
    }
})();




1 个答案:

答案 0 :(得分:1)

$ resource.query是异步的。 您的外部查询功能将在查询功能完成之前打印。

salesOrderResource.query(function (data) {
            vm.rowData = data;
            console.log("In query function:");
            console.log(vm.rowData);
        })

这将发生在第1位。

console.log("Outside query function:");
console.log(vm.rowData);

尝试用

替换它
setTimeout(function() {
    $scope.$apply(function () {
        console.log("Outside query function delayed:");
        console.log(vm.rowData);
    });
}, 1000);