0

I have a datatables.js table set up in an angular 1.2 project. I want a value from an $http.get(...) call to be what is displayed in one of the cells of each row of the table.

I know that $http returns a promise, but I can't figure out how to change the code so that the value of the resolved promise is what is returned by the render function so that the data & not the promise is what is displayed in the table.


UPDATED: Do I need to pre-fetch the data before the table is created? <-- This is the answer! See the selected answer for implementation. You can't make the call for every row within the table using something like Angulars $http because there is no opportunity to return the resolved promises data within the render function.


I'm not looking for a hack unless it is necessary. I would like to solve this with a known pattern.

Here is a fiddle of what I'm trying to do: jsfiddle example

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <div ng-app="salutationApp">
        <div ng-controller="salutationReportController">
            <table id="salutationTable" />
            <button type="button" ng-click="init()">
                Create Table
            </button>
        </div>
    </div>
    <script src="https://cdn.datatables.net/t/dt/jq-2.2.0,dt-1.10.11/datatables.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.js"></script>
    <script src="app.js"></script>
</body>
</html>

var salutationApp = angular.module("salutationApp", []);
salutationApp.controller("salutationReportController", ["$http", "$scope", function ($http, $scope) {
    var getSalutationLink = function (data) {
        var url = 'http://jsonplaceholder.typicode.com/posts/1';
        return $http({
            method: 'GET',
            url: url,
            params: data
        });
    };

    var init = function () {
        var salutationDataSource = [
          {
              salutationDataField: "hello!"
          },
          {
              salutationDataField: "good morning!"
          },
          {
              salutationDataField: "greeetings!"
          }
        ];

        $("#salutationTable").DataTable({
            "bDestroy": true,
            data: salutationDataSource,
            columns: [{
                title: "Salutation",
                data: "salutationDataField",
                render: function (cellData, type, fullRowData, meta) {
                    //I want this to return a some data from the server
                    var retVal = getSalutationLink({
                        salutation: cellData,
                    });

                    return retVal; // I know this is a promise... but I need to return the value of the resolved promise. I want the data from the web server to be the return value. This is where I'm stuck.
                }
            }]
        });

    };

    $scope.init = function () {
        init();
    };
}]);

Thanks!

2 Answers 2

1

I don't think your ng-controller would even work? You don't set it to a global variable name, it has to be declared within angular.

html

<div ng-controller="SalutationReportController">
    <div id="salutationTable"></div>
</div>

js

//this shouldn't work
var SalutationReportController = function() { /* blah */ }

//this would work
angular
    .module('app')
    .controller('SalutationReportController', ['$http', '$scope', function() {
        $http.get('/api/foobar').then(function(res) {
            //now the data you got from the promise is publicly available to your child directive
            $scope.tabledata = res.data;
        });
    }])

Somewhere in the code for your directive you'll need to add the correct scope properties and have the directive inherit the property according to its api.

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, sorry. I was just pulling pieces out of our project & renaming them while trying to figure out how to set up an angular app in jsfiddle and didn't do a very good job. I'll update the fiddle. Thanks for your contribution!
I think the moral of the story is that I need to get all of the data & associate it correctly before hand. Seeing your example lets me see that, now. I'll attempt this and get back with the results.
This is the basic example you'll see all over the place but it's the worst way to do it. Once you get it working switch to $resource or a library like js-data or restacular. The example I provided will only lead to spaghetti code.
0

Have you looked in to Angular-datatables?

http://l-lin.github.io/angular-datatables/#/withPromise

angular.module('showcase.withPromise', ['datatables', 'ngResource']).controller('WithPromiseCtrl', WithPromiseCtrl);

   function WithPromiseCtrl(DTOptionsBuilder, DTColumnBuilder, $resource) {
   var vm = this;
       vm.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
          return $resource('data.json').query().$promise;
   }).withPaginationType('full_numbers');

    vm.dtColumns = [
       DTColumnBuilder.newColumn('id').withTitle('ID'),
       DTColumnBuilder.newColumn('firstName').withTitle('First name'),
       DTColumnBuilder.newColumn('lastName').withTitle('Last name').notVisible()
  ];
}

3 Comments

I have seen it available, but this is the last requirement on this project & it might be difficult to meet deadlines if we switch over. From your experience, is it an easy switch? Tables we are using have a lot of customization already.
Basic functions should work in similar manner as with regular Datatables. They are just implimented in different ways. I recommend looking in to documentation and binding data with ng-repeat is always useful.
Thanks for the info! I started Datatables because I got a lot out of the box in a few lines of code. After that, any customization started to feel like I was doing an SAP implementation :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.