Data Table with Angularjs - javascript

I am using angularjs with MVC5 (.net) for creating single page website. I have problem to bind data with "data table(jquery)"
When first time bind data in to table at that time it's work fine but when i edit the record and rebind the data with data table at that time getting issue.
my code like bellow:
HTML
<table id="dt_Tarnsaction_Lunch" class="notinit">
<thead>
<tr>
<th >Employee Id</th>
<th >Edit</th>
</tr>
</thead>
<tbody id="TLunch">
<tr ng-repeat="TableRow in DashTranTableRows}" on-finish-tranlunch>
<td>{{TableRow.trancol_emplid}}</td>
<td >
<button ng-click="EditRecord(TableRow.trancol_dailytranspk)">
Edit
</button>
</td>
</tr>
</tbody>
</table>
"on-finish-tranlunch" Directive Code
appRoot.directive('onFinishTranlunch', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatTranlunchFinished');
});
}
}
}
});
My Code In Controller
$scope.LoadData();
var OTransLunchTable;
$scope.$on('ngRepeatTranlunchFinished', function (ngRepeatTranlunchFinishedEvent)
{
if (!null)
{
if ($("#dt_Tarnsaction_Lunch").hasClass("init"))
{
OTransLunchTable.fnDraw();
}
else
{
$("#dt_Tarnsaction_Lunch").removeClass("notinit");
$("#dt_Tarnsaction_Lunch").addClass("init");
OTransLunchTable = $('#dt_Tarnsaction_Lunch').dataTable({
"sPaginationType": "bootstrap",
"sDom": "R<'dt-top-row'Clf>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row'<'col-sm-6'i><'col-sm-6 text-right'p>>",
"fnInitComplete": function (oSettings, json) {
$('.ColVis_Button').addClass('btn btn-default btn-sm').html('Columns <i class="icon-arrow-down"></i>');
}
});
}
$('#dt_Tarnsaction_Lunch').width('100%');
}
else
{
$(".loading").hide();
alert("Error - Data can not be load");
}
});
My Code In Controller for load data first time as well as after edit record(both time i am using same method)
$scope.LoadData = function ()
{
myResource.getDashTableRows().then(function (d)
{
$scope.DashTranTableRows = d.data;
},
function (error) {
$(".loading").hide();
window.location = "login";
});
}
So, finally data loaded first time well and data table works fine at the first time but When i am edit record and load updated data at that time data table not loaded with updated data and also edit button not works.. :(
My JSON Format like bellow
[
{
"trancol_emplid": "a1",
"trancol_dailytranspk": 1
},
{
"trancol_emplid": "a2",
"trancol_dailytranspk": 2
},
{
"trancol_emplid": "a3",
"trancol_dailytranspk": 3
},
{
"trancol_emplid": "a4",
"trancol_dailytranspk": 4
},
{
"trancol_emplid": "a5",
"trancol_dailytranspk": 5
},
{
"trancol_emplid": "a6",
"trancol_dailytranspk": 6
}
]
My Service factory for load data from Server
angular.module('GratSyncSite').factory('myResource', function ($http)
{
var myResource =
{
getDashTableRows: function ()
{
$(".loading").show();
var promise = $http.get(WEBRESOURCEURL).success(function (response)
{
return response;
});
return promise;
}
}
});

Where are you posting your data? Is data even being received on server side?
On thing to note: MVC is not the best framework for SPAs. I would use ASP.NET WEB API (2.1) for server side.
That way API can be reused by 3rd party if you ever consider to open it to public.

Related

Get DataTables data from both local and REST sourced data

I want to use the jquery pluging datatables and complement local data through an external REST ressource.
My table has to columns, Id and RestCalledValue:
<table id="table">
<thead>
<tr>
<th>Id</th>
<th>RestCalledValue</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My js has an object data, which holds my local data:
let data = [
{
"id": 1
},
{
"id": 2
}
]
My datatables initialisation looks like below: i want to give the second column the returned value from the function getRestDataForId (id).
$(function () {
var table = $('#table').DataTable({
data: data,
columns: [
{
data: "id"
},
{
data: function (row, type, set, meta) {
getRestDataForId(row.id);
},
defaultContent: "-"
}
]
});
});
function getRestDataForId(id) {
fetch('https://jsonplaceholder.typicode.com/todos/' + id)
.then(response => response.json())
.then(data => data.title)
}
I constructed a fiddle here:
https://jsfiddle.net/mxhdwfz6/2/
I must be treating the promise wrong. Looking forward for your input!

ngTable with server side loading doen't update

I'm using ngTable to display a large table with data coming from the server. The initial data is displayed correctly. When I try sorting by a column or try going to the next page there is a request and correct response being sent and received, the getData function resolves it but the table isn't being updated in any way. It just shows the first page with the initial data.
HTML:
<table class="table table-bordered" ng-table-dynamic="table.detailsParams with table.cols" >
<tr ng-repeat="row in $data track by $index">
<td ng-repeat="col in $columns">{{::row[col.field]}}</td>
</tr>
</table>
JS:
scope.$on('campaign-changed', function (event, args) {
scope.campaign = args.campaign;
scope.campaign.createdAt = moment(scope.campaign.createdAt).format('DD MMM, YYYY')
scope.table.detailsParams = new NgTableParams({
count: 10,
sorting: { campaignName: "desc" }
}, {
getData: function (params) {
// ajax request to api
if (typeof params.total() == 'undefined' || params.total() == 0) {
ajaxSrv.getDetailsTotalCount(scope.campaign.id, function (data) {
params.total(data.data[0]);
})
}
var req = ajaxSrv.getCampaignData(params.url(), scope.campaign.id).then(function (response) {
return $q.resolve(response.data.data);
})
return $q.resolve(req);
}
});
})

ASP.NET MVC 6 Angular JS Table Update

I'm currently learning new MVC 6 and stucked completely with simple action - table data update on item selection change.The desired behaviour is to load questions that belong selected question block
I have angularJS factory:
(function () {
'use strict';
angular
.module('questionBlockApp')
.factory('questionBlockService', questionBlockService);
var questionBlockService = angular.module('questionBlockService', ['ngResource']);
questionBlockService.factory('Blocks', ['$resource',
function ($resource) {
return $resource('/api/blocks/', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
questionBlockService.factory('Questions', ['$resource',
function ($resource) {
return $resource('/api/blocks/:blockId', {blockId : '#blockId'}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
})();
Controller, which has refresh func (loadQuestions) built inside selection change function:
(function () {
'use strict';
angular
.module('questionBlockApp')
.controller('questionBlockController', questionBlockController);
//.controller('questionController', questionController);
questionBlockController.$inject = ['$scope', 'Blocks', 'Questions'];
//questionController.$inject = ['$scope', 'Questions'];
function questionBlockController($scope, Blocks, Questions) {
$scope.selectedBlock = 2;
if ($scope.Blocks == undefined | $scope.Blocks == null) {
$scope.Blocks = Blocks.query();
}
$scope.setSelected = function (blockId) {
$scope.selectedBlock = blockId;
$scope.loadQuestions();
}
$scope.loadQuestions = function () {
$scope.data = Questions.query({ blockId: $scope.selectedBlock });
$scope.data.$promise.then(function (data) {
$scope.Questions = data;
});
};
$scope.loadQuestions();
}
})();
And views:
View from which setSelected is called:
<table class="table table-striped table-condensed" ng-cloak ng-controller="questionBlockController">
<thead>
...
</thead>
<tbody>
<tr ng-repeat="block in Blocks" ng-click="setSelected(block.Id)" ng-class="{'selected': block.Id == selectedBlock}">
<td>{{block.Id}}</td>
<td>{{block.Name}}</td>
<td>{{block.Created}}</td>
</tr>
</tbody>
</table>
<table id="test" ng-controller="questionBlockController">
<thead>
<tr>
...
</tr>
</thead>
<tbody>
<tr ng-repeat="question in Questions">
<td>{{question.Id}}</td>
<td>{{question.Text}}</td>
<td>{{question.TimeLimit}}</td>
<td>{{question.Updated}}</td>
</tr>
</tbody>
</table>
When I click on different items in QuestionBlock table, $scope.Questions is updated properly, but the table does not reflect changes, as if no binding exists.
Okay, I am just a bit damaged.
There are two questionBlockController controllers defined, leading to intialization of different scopes => two $scope.Questions objects existence => refresh occured in Blocks scope, which was undesired behaviour.

Angularjs populating dropdown with in ng-repeat from different scope

Hi I have following controller which gets data from database using factory which works fine.
My service is
App.factory("pOvRepository", ['$resource', function ($resource) {
return {
pw: $resource('/api/pOv/:id', { id: '#id' }, { update: { method: 'PUT' } }),
ps: $resource('/api/pStatus/:id', { id: '#id' }, { update: { method: 'PUT' } })
};
}]);
Controller is
App.controller('pOvCtrl', function ($scope, pOvRepository, $location) {
$scope.poviews = pOvRepository.pw.query();
$scope.pS = pOvRepository.ps.query();
The data I get for $scope.pS is
[{"p_status1":"Up Coming","p_id":1,"proj":[]},
{"p_status1":"In Progress","p_id":2,"proj":[]},
{"p_status1":"On Hold","p_id":3,"proj":[]}]
In my html code I am trying to populate the dropdown with data from $scope.pS
<div ng-controller="pOvCtrl">
<form ng-repeat="p in poviews">
<input type="text" ng-model="p.include_in"/>
<select ng-model="p.p_id" ng-options="a.p_status1 as a.p_id for a in pS"></select>
</form>
When I run it, the dropdown does not get populated with the options from $scope.pS
Please let me know how I can fix it.
Thanks
Hard to tell without seeing your service, you need to specify a callback for the data:
pOvRepository.ps.query({}, function(data) {
$scope.pS = data;
});

Accessing LinkedIn API from AngularJS

I am building an app with Angular.js accesing the LinkedIn API. What happens is that when I do a call to the API, the model does not get refreshed inmediately, but after I do another change on the screen. For example, I have binded the API call to a button, but I have to press it twice for the screen to get the data refreshed. This is my controller:
angbootApp.controller('AppCtrl', function AppCtrl($scope, $http) {
$scope.getCommitData = function() {
IN.API.Profile("me").fields(
[ "id", "firstName", "lastName", "pictureUrl",
"publicProfileUrl" ]).result(function(result) {
//set the model
$scope.jsondata = result.values[0];
}).error(function(err) {
$scope.error = err;
});
};
});
And this is my button and a link with the content:
<div>
{{jsondata.firstName}}
<form ng-submit="getCommitData()">
<input type="submit" value="Get Data">
</form>
</div>
EDIT: Explanation on how I did it here
You need to call $scope.$apply when retrieving the results/error
angbootApp.controller('AppCtrl', function AppCtrl($scope, $http) {
$scope.getCommitData = function() {
IN.API.Profile("me").fields(
[ "id", "firstName", "lastName", "pictureUrl",
"publicProfileUrl" ]).result(function(result) {
//set the model
$scope.$apply(function() {
$scope.jsondata = result.values[0];
});
}).error(function(err) {
$scope.$apply(function() {
$scope.error = err;
});
});
};
});
Anything outside angular world does not trigger automatic refresh of the views.
See $apply

Categories