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!