angularjscallbackhandsontableangularjs-digest

Trigger the digest cycle in callback events


I want to create a corresponding textarea along with a handstontable, such that modifying the table has impact to the text, and vice-versa. Here is a JSBin.

<!DOCTYPE html>
<html>
<head>
    <script src="https://handsontable.github.io/ngHandsontable/node_modules/angular/angular.js"></script>
    <script src="https://docs.handsontable.com/pro/1.8.2/bower_components/handsontable-pro/dist/handsontable.full.js"></script>
    <link type="text/css" rel="stylesheet" href="https://docs.handsontable.com/pro/1.8.2/bower_components/handsontable-pro/dist/handsontable.full.min.css">
    <script src="https://handsontable.github.io/ngHandsontable/dist/ngHandsontable.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="Ctrl">
        <hot-table settings="settings" on-after-create-row="onAfterCreateRow" datarows="dataJson"></hot-table>
        <br><br>
        <textarea cols=40 rows=20 ng-model="dataString"></textarea>
    </div>
    <script>
    var app = angular.module('app', ['ngHandsontable']);
    app.controller('Ctrl', ['$scope', '$filter', 'hotRegisterer', function ($scope, $filter, hotRegisterer) {
        $scope.dataJson = [[5, 6], [7, 8]];

        $scope.onAfterCreateRow = function (index, amount) {
            $scope.$digest();
        };

        $scope.$watch('dataJson', function (dataJson_new) {
            $scope.dataString = $filter('json')(dataJson_new);
        }, true);

        $scope.$watch('dataString', function (dataString_new) {
            try {
                $scope.dataJson = JSON.parse(dataString_new);
            } catch (e) {
            }
        }, true);

        $scope.settings = {
            contextMenu: true,
            contextMenuCopyPaste: {
                swfPath: 'zeroclipboard/dist/ZeroClipboard.swf'
            }
        };
    }]);
    </script>
</body>
</html>

However, one thing I realise is that, adding/deleting rows/columns will NOT fire the watcher of dataJSON (whereas modifying a cell value will do). So I have to use $scope.$digest() in the callbacks such as onAfterCreateRow to reflect the change of adding rows. But it raises Uncaught TypeError: Cannot set property 'forceFullRender' of null:

screen shot 2017-02-01 at 17 07 55

Having $scope.$digest() in other callbacks (i.e., onAfterCreateCol, onAfterRemoveRow and onAfterRemoveCol) will raise the same error. I think it is a serious problem, if we cannot well trigger the digest cycle in these callback events. Does anyone know how to solve this or have any workaround?


Solution

  • The $timeout was a workaround in some older versions of angular currently, you can use $applyAsync that was created to replace the $timeout as workaround and work for the cases where you would get an error $digest already in progress