Search code examples
javascriptangularjshandsontable

ngHandsontable datarow undefined after asynchronous service call


I have a simple controller that makes an ajax call to fetch table data for an ngHandsontable, but the datarows value is undefined.

var app = angular.module('propnet', [
    'ngRoute',
    'ngHandsontable'
]);
// configure our routes
app.config(function($routeProvider)
{
    $routeProvider.    
    // route for the about page
    when('/property/:prop_id',
    {
        templateUrl: 'pages/property.html',
        controller: 'propertyController'
    })
...

app.controller('propertyController', function($scope, $routeParams, $http, $log)
{
    $http.get('api/Transactions/property/' + $routeParams.prop_id).success(function(data)
    {
        $scope.transactions = data;
        $log.log("Got some txns" + data);
    });

});

pages/property.html:

<div class="row">{{ transactions }}</div>
<div class='row'>
    <hot-table col-headers="showColHeaders" datarows="transactions">
        <hot-column data="itemName" title="'Name'" type="'text'" read-only></hot-column>
         <hot-column data="amount" title="'Amount'" type="'numeric'" format="'$ 0,0.00'" read-only></hot-column>
         <hot-column data="date" title="'Date'" type="'date'" dateFormat="'YYYY-MM-DD'"></hot-column>
         <hot-column data="vendorName" title="'Vendor'"></hot-column>
         <hot-column data="notes" title="'Notes'"  width="150" ></hot-column>
    </hot-table>
</div>

{{ transactions }} prints the value returned from the service call, but the <hot-table> is empty, and ngHandsontable is throwing the error (multiple times):

Got some txns[object Object],[object Object],[object Object],[object Object]

angular.js:12477 TypeError: Cannot read property 'length' of undefined
    at Object.fn (ngHandsontable.js:253)
    at Scope.$digest (angular.js:15826)
    at Scope.$apply (angular.js:16097)
    at done (angular.js:10546)
    at completeRequest (angular.js:10744)
    at XMLHttpRequest.requestLoaded (angular.js:10685)(anonymous function) @ angular.js:12477(anonymous function) @ angular.js:9246Scope.$digest @ angular.js:15844Scope.$apply @ angular.js:16097done @ angular.js:10546completeRequest @ angular.js:10744requestLoaded @ angular.js:10685

Why isn't $scope.transactions getting bound to datarows?

Related: ngHandsontable shows no content on rest service call


Solution

  • Initialize the $scope.transactions = [] in your controller. Initially when handsontable try to bind the data $scope.transactions is undefined. So by initializing it first helps to get pass the error. Once the GET method returns the data handsontable will populate the table with data.