Search code examples
jsonangularjsng-gridgspgrails-domain-class

Angularjs ng-grid using Grails JSON data


Angular ng-grid data binding question

I have a Groovy/Grails application that has a domain “Grid” class for which I have registered a custom “marshaller” to produce the JSON that I can use for an Angularjs ng-grid..

Say “grid” is and instance of the Grid class, “grid as JSON” produces the desired JSON.

I have a Grails/groovy controller that loads the data and returns the JSON:

def index() {
    def grid = Grid.first()
    grid as JSON
}

But I don’t know how to get this JSON data into the ng-grid in my GSP:

<body ng-controller="MyCtrl">
    <script>
    var app = angular.module('myApp', ['ngGrid']);

    app.controller('MyCtrl', function($scope) {

        $scope.gridOptions = ${grid};  // NEED HELP HERE !
    });
    </script>

    <div class="gridStyle" ng-grid="gridOptions"></div>
</body>

I don't know how to get the data into $scope.gridOptions. When I look at what is being generated with firebug, I see $scope.gridOptions is

{&quot;columnDefs&quot;:[{&quot;field&quot;: ...

which is the encoded JSON data. (The quotation marks are encoded). What is the best way to pass JSON data between a Grails back end and ng-grid in a JSP?


Solution

  • Thank you for the suggestion Sridhar, I started looking for ways to un-escape JSON within GSP, and I found the answer here:

    how-to-render-json-properly-without-escaping-quotes-inside-a-gsp-script-tag

    I need to use the g:applyCodec tag in my GSP:

    <g:applyCodec encodeAs="none">
         $scope.gridOptions = ${grid};
    </g:applyCodec>