How to render angular ng if/show within database - javascript

current I am working with a combination of datatables + angularjs. I'm following documentation here. https://l-lin.github.io/angular-datatables/archives/#!/gettingStarted
My table is rendering and getting populated with angularjs code. The issue I am coming across is I only want the photo text to appear only when it exist. When I inspect the element, ng-hide is always set. It'll appear fine if I remove ng-if.
Code
<table datatable="ng" class="contact-grid-table row-border" dt-options="vm.dtOptions2" dt-column-defs="vm.dtColumnDefs" dt-instance="dtInstanceCallback" id="tableId">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Photo</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in vm.contacts">
<td>{{contact.firstName}}</td>
<td>{{contact.lastName}}</td>
<td><span ng-if="contact.photo">{{contact.photo}}</span></td>
</tr>
</tbody>
</table>
I also tried the suggestion here ng-show not working in datatables columns but my table will no longer load. Page just freezes.
May I ask if there's any suggestions on how to get ng-if/show to work with datatables.
vm.dtOptions2 = DTOptionsBuilder.newOptions()
.withOption('createdRow', function (row, data, dataIndex) {
// Recompiling so we can bind Angular directive to the DT
$compile(angular.element(row).contents())($scope);
})
.withOption('headerCallback', function (header) {
if (!vm.headerCompiled) {
// Use this headerCompiled field to only compile header once
vm.headerCompiled = true;
$compile(angular.element(header).contents())($scope);
}
})
.withPaginationType('full_numbers').withOption('responsive', true)
.withColReorder()
.withColReorderOrder([0,1, 2,3])
.withScroller()
.withOption('bFilter', false) // for search box
.withOption('bInfo', false) // for showing counts at the bottom
.withOption('deferRender', true)
.withOption('scrollY', 200)
// Set order
// Fix last right column
.withDisplayLength(2)
.withFixedHeader({
bottom: false
});

Related

How pick up checkbox result in post method angularjs

I have a table that sets out a list of rules. When the checkboxes are clicked, I need them to take this "true" value and post to an API endpoint. This has been set up, but what I am getting back is that "associated_rule" is undefined.
I have tried setting $scope.associated_rule.selected = true; in my controller, but this still doesn't define the variable and throws up the same error in the console.
Here is my HTML form:
<form name="rules_form" method="post" ng-submit="attach()">
<table class="table table-striped table-hover" ng-model="associated_rules">
<thead>
<th>Rule Types:</th>
<th>Description:</th>
<th>Start Time:</th>
<th>End Time:</th>
<th>Apply Rule to Vehicle:</th>
</thead>
<tr ng-repeat="associated_rule in associated_rules">
<td>#{{ associated_rule.resource_ids.accounts }}</td>
<td>#{{ associated_rule.description }}</td>
<td>#{{ associated_rule.start_time }}</td>
<td>#{{ associated_rule.end_time }}</td>
<td><input type="checkbox" ng-model="associated_rule.selected" aria-label="rule"></td>
</tr>
</table>
<button class="btn btn-primary" ng-click="attach()">Attach</button>
</form>
My Controller event:
$scope.attach = function () {
$scope.associated_rule.selected = true;
var i;
for (i = 0; i < $scope.associated_rule.selected.length; i++) {
//need to create a loop where the true value is picked up and then I can send the data using a POST method. But I'm stuck on this.
}
console.log(the result of the event);
};
For now, I just want the results to console.log, so I can see that the event is creating the loop and displaying the results. After that, I should be OK.
Any help would be much appreciated.
I have fixed this by defining the $scope.rule as an empty array and setting the $scope.rule.selected to "false" by default.
Great! step one! But the checkboxes are ALL selecting when you click A checkbox - think this may be the ng-repeat causing me a pain in the backside.
$scope.rule = [];
$scope.rule.selected = false;
So, how do I ensure that only the checkboxes set that I select and not all at once?
Fixed this too; as the above was just making the entire array selected; as i wasn't drilling down into the array. This did it:
ng-model="rules.selected[associated_rule.id]"
by modelling the a rule within that defined array, it shows up when testing. Brill. :)
By mistake you are changing the value of your check box on clicking the button:
$scope.associated_rule.selected = true;
This will give the current value, selected or not selected
$log.log($scope.associated_rule.selected);

angularjs smart-table programmatically sort

I have a table set up using the smart-table plug in for AngularJS. Everything appears to work nicely. Rather than having the user click on the table header to trigger a sort, I'd like to programmatically trigger sorting from my Angular controller. I do not see a way of doing this in the documentation here:
http://lorenzofox3.github.io/smart-table-website/
Am I overlooking something?
Found this on JSFiddle, might help you: http://jsfiddle.net/vojtajina/js64b/14/
<script type="text/javascript" ng:autobind
src="http://code.angularjs.org/0.10.5/angular-0.10.5.js"></script>
<table ng:controller="SortableTableCtrl">
<thead>
<tr>
<th ng:repeat="(i,th) in head" ng:class="selectedCls(i)" ng:click="changeSorting(i)">{{th}}</th>
</tr>
</thead>
<tbody>
<tr ng:repeat="row in body.$orderBy(sort.column, sort.descending)">
<td>{{row.a}}</td>
<td>{{row.b}}</td>
<td>{{row.c}}</td>
</tr>
</tbody>
</table>
A quick hack i found on how to do this is by setting the table header st-sort property and then triggering a click() on that element
<tr>
<th id="myelement" st-sort="date" st-sort-default="reverse">Date</th>
...
</tr>
Then later:
setTimeout(function() {
document.getElementById('myelement').click()
},
0);
Here is the 'angular' way to do this. Write a directive. This directive will have access to the smart table controller. It will be able to call the controller's sort by function. We will name the new directive stSortBy.
The below HTML includes the standard smart table syntatic sugar. The only new attribute directive here is st-sort-by. That's where the magic will happen. It's bound to a scoped variable sortByColumn. This is a string value of the column to sort
<table st-sort-by="{{sortByColumn"}}" st-table="displayedCollection" st-safe-src="rowCollection">
<thead>
<tr>
<th st-sort="column1">Person</th>
<th st-sort="column2">Person</th>
</tr>
</thead>
</table>
<button ng-click="toggleSort()">Toggle sort columns!</button>
Here is the stSortBy directive that hooks into the st table controller
app.directive('stSortBy', function() {
return {
require: 'stTable',
link: function (scope, element, attr, ctrl) {
attr.$observe('stSortBy', function (newValue) {
if(newValue) {
// ctrl is the smart table controller
// the second parameter is for the sort order
ctrl.sortBy(newValue, true);
}
});
}
};
});
Here is the controller. The controller sets the sort by in it's scope
app.controller("MyTableWrapperCtrl", ["$scope", function($scope) {
$scope.sortByColumn = 'column2';
$scope.toggleSort = function() {
$scope.sortByColumn = $scope.sortByColumn === 'column2' ? 'column1' : 'column2';
// The time out is here to guarantee the attribute selector in the directive
// fires. This is useful is you do a programmatic sort and then the user sorts
// and you want to programmatically sort back to the same column. This forces a sort, even if you are sorting the same column twice.
$timeout(function(){
$scope.sortByColumn = undefined;
}, 0);
};
}]);

Angular Datatables REST based per page data with explicit table rendering

I have followed the approach "DataTables: Custom Response Handling" by Fabrício Matté. However, my requirement is to avoid rendering of table's rows and columns via callback. Instead, would like to traverse the current ajax request returned json data and render explicit html (tr/td) to have more control. Due to this, currently i see data shown twice on my table. At the same time, i understand that callback is rendering the page related buttons: prev, 1,2 next etc and click events which i would like to reuse and wan't to avoid custom implementation.
JS:
function notificationsCtrl($scope,$http,$resource, DTOptionsBuilder, DTColumnBuilder) {
var vm = this;
vm.notifications = [];
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withOption('serverSide', true)
.withOption('ajax', function(data, callback, settings) {
// make an ajax request using data.start and data.length
$http.get('notifications/list?page=' + (((data.start)/10)+1)).success(function(res) {
// map your server's response to the DataTables format and pass it to
// DataTables' callback
callback({
recordsTotal: 120,
recordsFiltered: 120,
data: res
});
vm.notifications = res;
});
})
.withDataProp('data') // IMPORTANT¹
.withOption('processing', true)
.withPaginationType('full_numbers');
$scope.dtColumns = [
DTColumnBuilder.newColumn('notificationId').withTitle('notificationId'),
DTColumnBuilder.newColumn('createUserId').withTitle('createUserId'),
DTColumnBuilder.newColumn('Language').withTitle('language')
];
}
HTML: sample but actual will require extra processing for some of the td tags
<table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Language</th>
<th>Last Updated</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="notification in wynkCMSToolApp.notifications">
<td>{{ notification.notificationId }}</td>
<td>{{ notification.title }}</td>
<td>{{ notification.Language }}</td>
</tr>
</tbody>
</table>
If you want to render directly in the HTML, consider using the Angular renderer. However, such renderer does not support the server side processing.
So I recommend you use the server side processing along with the columns.render function.
Here an example of using the render function.

How can I refresh a datatable inside a div using JavaScript?

Here is my code:
oTable2 = $('#BigData2').dataTable({
"bLengthChange":false,
"bPaginate":false,
"oLanguage": {
"sZeroRecords": "No records found"
},
"sAjaxSource":'StatusSrv',
// "sDom":'RCT<"clear">lfrtip',
//"aoColumnDefs":[{}]
})
var auto_refresh = setInterval(
function (){
$('#Status_Table').fadeOut('slow').load('SupplyPlanning.jsp
#oTable2.fnDraw()').fadeIn("slow");
}, 6000);
<div id="Status_Table" class="chartFloatLeftInner">
<table id="BigData2" >
<thead >
<tr>
<th><input type="checkbox" onClick="checkall()" name="maincheck" id="maincheck"/></th>
<th title="REQ_NO">REQ_NO</th>
<th title="Retailer Partner number">Retailer num</th>
<th title="STATUS">OVERALL_STATUS</th>
</tr>
</thead>
<tbody></tbody>
</table>
I want to refresh my datatable in a particular time interval so that I am using fndraw but it only redraws the table with the old data. If I insert new data in the database, the new data is not shown after refresh; it shows only the old data.
Probably you would need to add the "bDestroy": true attribute to your datatable code which allow you to rebuild it otherwise once created you can not load it with new data.
Try using append:
$('#Status_Table').append( your table in here);
It work for me

JQuery tablesorter appended data not sorting

Im trying too append data to a table with the tablesorter plugin (http://tablesorter.com)
Im using the following code:
<table id="sortme" border="1" style="width: 200px;">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<td>will</td>
<td>smith</td>
<td>1</td>
</tr>
...................
</tbody>
</table>
Click me!
And:
$(document).ready(function() {
var i = 5;
$("#sortme").tablesorter({
sortList: [[2,0]]
});
$("#test").click(function() {
$("#sortme tbody").append('<tr><td>NEW</td><td>NEW</td><td>'+(i++)+'</td></tr>');
$("#sortme").trigger("update");
var s = [[2,0]];
$("#sortme").trigger("sorton",[s]);
return false;
});
});
Problem is the appended row stays at top, why?
See example: http://jsfiddle.net/jmU3Z/8/
In case anyone else stumbles across this.
By the time the "sorton" event is handled the DOM hasn't been assigned the table.config.parsers. The "sorton" event handling needs to be wrapped in a 1 millisecond timeout.
Replace the existing "sorton" bind in jquery.tablesorter.js (line ~803) with the following:
}).bind("sorton", function (e, list) {
var me = this;
setTimeout(function () {
$(this).trigger("sortStart");
config.sortList = list;
// update and store the sortlist
var sortList = config.sortList;
// update header count index
updateHeaderSortCount(me, sortList);
// set css for headers
setHeadersCss(me, $headers, sortList, sortCSS);
// sort the table and append it to the dom
appendToTable(me, multisort(me, sortList, cache));
}, 1);
You're problem is the [s]. You're sort parameter is already an array, just pass it the var not the var in an array.
$("#sortme").trigger("sorton",s);
Works for me, FF4.

Categories

Resources