Footable3 and angularjs - angularjs

I am having an issue getting footable3 working with angularjs. Everything seems to be working as expected; however, footable3 is removing any <a/> links in the table cells. Code below, but if I remove the attribute "my-footable" the links appear (inspect the table, there are <a/> links), but I can't figure out why they are removed when using the directive (inspect the table, there are no <a/> links)
I used angularjs/footable as a starting point
Here is my directive
app.directive('myFootable', function () {
return function (scope, element) {
var footableTable = element.parents('table');
if (!scope.$last) {
return false;
}
scope.$evalAsync(function () {
if (!footableTable.hasClass('footable-loaded')) {
footableTable.footable();
}
footableTable.data('__FooTable__').draw();
});
};
}
and here is my table
<table class="table footable">
<thead>
<tr>
<th>Team</th>
<th>Player</th>
<th data-breakpoints="xs sm" data-type="number">Games</th>
<th data-sorted="true" data-direction="DESC" data-type="number">Points</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in players" my-footable>
<td>{{item.teamName}}</td>
<td>{{item.playerName}}</td>
<td class="text-right">{{item.games}}</td>
<td class="text-right">{{item.points}}</td>
</tr>
</tbody>
</table>

got it to work by changing the directive to:
function () {
return function ($compile, scope, element) {
if (!scope.$last) {
return false;
}
var footableTable = element.parents('table');
scope.$evalAsync(function () {
if (!footableTable.hasClass('footable-loaded')) {
footableTable.footable();
}
footableTable.data('__FooTable__').draw();
$compile(element.contents())(scope);
});
};
}

Related

Controller function not call in Angular module md-data-table

As per documentation of "md-data-table". I have implemented datatable. But function getDesserts is not calling.
Service code is as below
return {
'getPagingData': function (params) {
var defered = $q.defer();
console.log("Get Paging Service...");
pagination.getPagingData(params,function (response) {
defered.resolve(response);
},
function (error) {
defered.reject(error);
});
return defered.promise;
}
}
And Controller code is as below
$scope.selected = [];
$scope.queryy = {
order: 'name',
limit: 5,
page: 1,
className :"Sla"
};
function success(desserts) {
alert("d");
$scope.desserts = desserts;
}
$scope.getDesserts = function () {
alert("d");
//$scope.promise = $nutrition.desserts.get($scope.query, success).$promise;
$scope.promise = pagingService.getPagingDataHttp($scope.queryy, success).$promise;
};
My html code is as below
<!-- exact table from live demo -->
<md-table-container>
<table md-table md-row-select multiple ng-model="selected" md-progress="promise">
<thead md-head md-order="query.order" md-on-reorder="getDesserts">
<tr md-row>
<th md-column md-order-by="nameToLower"><span>Dessert (100g serving)</span></th>
</tr>
</thead>
<tbody md-body>
<tr md-row md-select="dessert" md-select-id="name" md-auto-select ng-repeat="dessert in desserts.data">
<td md-cell>{{dessert.name}}</td>
</tr>
</tbody>
</table>
</md-table-container>
<md-table-pagination md-limit="query.limit" md-limit-options="[5, 10, 15]" md-page="query.page" md-total="{{desserts.count}}" md-on-paginate="getDesserts" md-page-select></md-table-pagination>
After this implementation, getDessert function in controller is not being
called. Kindly guide me

AngularJS - DOM not updated in Chrome and Mozilla

I'm using angularjs and angular-ui-bootstrap to make a table and page some data, which I get from an API.
I've made sure my service receives the correct data and that the requests are built properly. My pageChange function is properly triggered and my first page gets loaded successfully.
So I have the following controller setup:
(function () {
'use strict';
initContacts.$inject = ['$scope', '$http'];
angular.module('app')
.config(function ($locationProvider) {
$locationProvider.html5Mode(true);
});
angular.module('app', ['ui.bootstrap']).controller('contactSearchController', initContacts);
function initContacts($scope, $http) {
$scope.contacts = [];
$scope.totalItems = 0;
$scope.pages = 0;
$scope.currentPage = 0;
$scope.maxPageLinksShown = 5;
if (window.location.hash !== '') {
$scope.currentPage = window.location.hash.replace('#', '');
}
$http.get("/api/ContactApi/GetPage?pageIndex=" + ($scope.currentPage - 1)).success(function (data) {
$scope.contacts = data.Contacts;
$scope.totalItems = data.Count;
$scope.PageSize = data.Contacts.length;
$scope.pages = Math.ceil((data.Count / $scope.PageSize));
});
$scope.pageChanged = function () {
$http.get("/api/ContactApi/GetPage?pageIndex=" + ($scope.currentPage - 1))
.success(function (data) {
$scope.contacts = data.Contacts;
});
};
}
}
})();
And in my view I have:
<div ng-app="app" ng-controller="contactSearchController">
<table class="table table-striped table-hover contact-search-table">
<thead>
<tr>
<td class="contact-title">
Titel
</td>
<td class="department">
Afdeling
</td>
<td class="name">
Navn
</td>
<td class="work-phone">
Telefon
</td>
<td class="mobile">
Mobile
</td>
<td class="email">
Email
</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in contacts">
<td class="contact-title">{{value.Title}}</td>
<td class="department">{{value.Department}}</td>
<td class="name">{{value.FullName}}</td>
<td class="work-phone">{{value.WorkPhone}}</td>
<td class="mobile">{{value.WorkMobile}}</td>
<td class="email">{{value.Email}}</td>
</tr>
</tbody>
</table>
<div class="col-xs-12 pager-container">
<ul uib-pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" max-size="maxPageLinksShown" class="pagination-sm" boundary-links="true" num-pages="pages"></ul>
</div>
Now this works to some extent.
My problem
When I click the page links, the pageChanged() function is called, I get the data from my api and it's all correct, the list in the scope appears to be updated fine, but the table in my view doesn't change.
This solution works fine ONLY in IE ! (who would have thought huh...)
No exceptions get thrown.
I swear this was working yesterday.
Any help is much appreciated!
EDIT
What I've tried:
-Putting the assignment of the contacts in an $apply like so:
$scope.pageChanged = function () {
$http.get("/api/ContactApi/GetPage?pageIndex=" + ($scope.currentPage - 1))
.success(function (data) {
$scope.$apply(function () { // apply
$scope.contacts = data.Contacts;
});
});
};
I got a "$digest already in progress" error from this.
tried to wrap the apply in a timeout like so:
$timeout(function(){ //any code in here will automatically have an apply run afterwards });
Got rid of the error but the DOM still won't update.
I had such a problem and I solved it using $scope.$apply:
$scope.pageChanged = function () {
$http.get("/api/ContactApi/GetPage?pageIndex=" + ($scope.currentPage - 1))
.success(function (data) {
$scope.$apply(function () { // apply
$scope.contacts = data.Contacts;
});
});
};
You should use $scope.$applyAsync instead. It will be applied to the next digest cycle.
If you need to target all the $scopes of your AngularJS application, use $rootScope.$applyAsync instead.
Official doc
Okay so what worked in this situation was changing the way I'm visualizing the ng-repeat like so:
<tr ng-repeat="contact in getContacts()">
<td class="contact-title">{{contact.Title}}</td>
<td class="department">{{contact.Department}}</td>
<td class="name">{{contact.FullName}}</td>
<td class="work-phone">{{contact.WorkPhone}}</td>
<td class="mobile">{{contact.WorkMobile}}</td>
<td class="email">{{contact.Email}}</td>
</tr>
And heres the getContacts() function:
$scope.getContacts = function () {
var data = $scope.contacts;
if (data instanceof Array) {
return data;
} else {
return [data];
}
}
I don't really know why that works, but it does.

Angular directive showing in the wrong place

I have the following page
<body ng-controller="myController">
<table>
<tbody>
<tr ng-repeat="r in rows">
<div show-row></div>
</tr>
</tbody>
</table>
</body>
with the following Angular module
ng.module('myModule', [ ])
.controller('myController', ['$scope', function ($scope) {
$scope.rows = [a non-empty array of values]
}]).directive('showRow', function () {
return {
replace: true,
template: '<td>Hello!</td>'
};
});
My problem is that Hello! is shown once before the table and not, as I would expect, once for every row of the table.
I guess I have to use the scope property for the directive, but how?
The problem is with div which cannot be a children to tr. Change the div to td.
<body ng-controller="myController">
<table>
<tbody>
<tr ng-repeat="r in rows">
<td show-row></td>
</tr>
</tbody>
</table>
</body>
I'm having a similar problem with the following layout:
<table>
<table-header data="headers" order="order"></table-header>
<tbody>
<tr ng-repeat="...">
...
</tr>
</tbody>
</table>
The tableHeader directive looks like this:
.directive('tableHeader', [function () {
return {
restrict: 'E',
replace: true,
scope: {
data: '=',
order: '='
},
template: '\
<thead><tr> \
<th ng-repeat="header in ::data" \
ng-click="orderBy(header)"> \
{{:: header.name }} \
</th> \
</tr></thead>',
link: function (scope, elem, attrs) {
scope.orderBy = function (header) {
if (scope.order.by === header.prop) {
scope.order.reverse = !scope.order.reverse;
} else {
scope.order.by = header.prop;
}
};
}
};
Weird enough, the thead element ends up out of the table, instead of inside.
Edit: seems to be documented in https://github.com/angular/angular.js/issues/7295.

Angular directive doesn't work properly inside an HTML table

I'm trying to use an AngularJS (1.2) directive to create row cells inside an HTML Table and I don't understand why Angular inserts the directive result as first child of 'body' instead of replacing the original directive element?
Here is the HTML markup:
<body ng-app="myApp" ng-controller="MainCtrl">
<table>
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
</tr>
</thead>
<tbody>
<my-directive></my-directive>
</tbody>
</table>
</body>
And the directive:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.data = ['value1','value2','value3','value4'];
});
app.directive('myDirective', function () {
return {
restrict: "E",
replace: true,
scope:false,
link: function (scope, element) {
var html = angular.element('<tr></tr>');
angular.forEach(scope.data, function(value, index) {
html.append('<td>'+value+'</td>');
});
element.replaceWith(html);
}
};
});
Please use the Plunker link below to see the result:
http://plnkr.co/edit/zc00RIUHWNYW36lY5rgv?p=preview
It seems to work better if you dont restrict the directive to be an element:
app.directive('myDirective', function () {
return {
restrict: "A",
replace: true,
scope:false,
link: function (scope, element) {
var html = angular.element('<tr></tr>');
angular.forEach(scope.data, function(value, index) {
html.append('<td>'+value+'</td>');
});
element.replaceWith(html);
}
};
});
<table>
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
</tr>
</thead>
<tbody>
<tr my-directive></tr>
</tbody>
</table>

setting ng-href in <tr> elements

The following code makes the client.name an anchor on each client in clients. I am interested in having the entire <tr> element be that link however. ng-href does not work on the <tr> element.. what can I do so that the entire row is a single link instantiated by ng-href?
<tr ng-repeat="client in clients">
<td><a ng-href="#/user/{{client.tagid}}">{{client.firstname}}</a></td>
<td>{{client.lastname}}</td>
<td>{{client.inumber}}</td>
</tr>
What I am looking to do is something like this.. which of course does not work..
<a ng-href="#/user/{{client.tagid}}">
<tr ng-repeat="client in clients">
<td>{{client.firstname}}</td>
<td>{{client.lastname}}</td>
<td>{{client.inumber}}</td>
</tr>
</a>
OR
<tr ng-repeat="client in clients" ng-href="#/user/{{client.tagid}}">
<td>{{client.firstname}}</td>
<td>{{client.lastname}}</td>
<td>{{client.inumber}}</td>
</tr>
You can use an ng-click (instead of onClick) as Jason suggests as well.
Something like:
HTML
<tr ng-repeat="client in clients" ng-click="showClient(client)">
<td><a ng-href="#/user/{{client.tagid}}">{{client.firstname}}</a></td>
<td>{{client.lastname}}</td>
<td>{{client.inumber}}</td>
</tr>
Controller
$scope.showClient = function(client) {
$location.path('#/user/' + client.tagid);
};
And styling to make it show as an clickable element (wont work in IE7)
CSS
tr {
cursor: pointer;
}
// or
[ng-click] {
cursor: pointer;
}
I wrote a directive so that you can simply write:
<tr ng-repeat="client in clients" such-href="#/user/{{client.tagid}}">
The source:
app.directive('suchHref', ['$location', function ($location) {
return{
restrict: 'A',
link: function (scope, element, attr) {
element.attr('style', 'cursor:pointer');
element.on('click', function(){
$location.url(attr.suchHref)
scope.$apply();
});
}
}
}]);
I use my own Angular directive that automatically wraps every cell in the row with a link.
The advantages are:
You don't duplicate code.
There is a regular link in every cell so things like "Open in new tab" (middle button or CTRL+click) works as expected (in opposite of the ng-click version).
HTML usage:
<tr row-href="#/user/{{client.tagid}}">
<td>...</td>
<td>...</td>
</tr>
Directive code (in TypeSript):
export class RowHrefDirective implements ng.IDirective {
constructor(private $compile: ng.ICompileService) {
}
restrict = "A";
scope = {
rowHref: "#rowHref"
};
link = (scope: Scope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes): void => {
const cells = element.children("td[skip-href!='yes'],th[skip-href!='yes']");
cells.addClass("cell-link");
for (const cell of cells.toArray()) {
const link = jQuery(`<a ng-href="{{ rowHref }}"></a>`);
this.$compile(link)(scope);
jQuery(cell).prepend(link);
}
}
}
Required CSS code (to fill the whole cell with the link):
td.cell-link,
th.cell-link {
position: relative;
}
td.cell-link a,
th.cell-link a {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
}
This is a CSS and HTML issue, not specific to AngularJS. The only allowed child of a <tr> is a <td>, and so you need to wrap the content of each cell in an anchor. You also need to make the anchor a block element to make it the full height/width of its container:
<tr ng-repeat="client in clients">
<td>
<a style="display: block;" ng-href="#/user/{{client.tagid}}">
{{client.firstname}}
</a>
</td>
<td>
<a style="display: block;" ng-href="#/user/{{client.tagid}}">
{{client.lastname}}
</a>
</td>
<td>
<a style="display: block;" ng-href="#/user/{{client.tagid}}">
{{client.inumber}}
</a>
</td>
</tr>
<tr ng-repeat="client in clients" ng-href="#/user/{{client.tagid}}">
<td>{{client.firstname}}</td>
<td>{{client.lastname}}</td>
<td>{{client.inumber}}</td>
</tr>
This is with the referrence to the options provided which may work.
I think this binds the entire row with the each field in the row. but is not clickable. how to do that. i mean we should be able to click so that another view/module can be open.
As requested by #sfs, here’s the solution which we’re using for ui-sref (Angular 1.5; TypeScript code, apologies for any inconvenience).
Credits: The code is based on the awesome answer by Martin Volek:
import { IDirective, IDirectiveFactory, ICompileService, forEach, element } from 'angular';
export default class RowUiSrefDirective implements IDirective {
restrict = 'A';
scope = { rowUiSref: '#rowUiSref' };
constructor(private $compile: ICompileService) { }
link = (scope, elm, attrs) => {
if (elm[0].tagName !== 'TR') {
throw new Error('This directive should only be used in <tr> elements.');
}
forEach(elm.children(), (cell) => {
if (cell.attributes['skip-href'] && cell.attributes['skip-href'].value !== 'false') {
return;
}
cell.className += ' cell-link';
let link = element('<a ui-sref="{{rowUiSref}}"></a>');
this.$compile(link)(scope);
element(cell).prepend(link);
});
};
static factory(): IDirectiveFactory {
let directive = ($compile: ICompileService) => new RowUiSrefDirective($compile);
directive.$inject = ['$compile'];
return directive;
};
}
Directive initialization:
import { module } from 'angular';
import RowUiSrefDirective from './rowUiSref';
module('app').directive('rowUiSref', RowUiSrefDirective.factory());
Example usage:
<table>
<tr ng-repeat="item in itemController.items"
row-ui-sref="state.item({itemId: '{{item.id}}'})">
<td>{{item.name}}</td>
<td>{{item.label}}</td>
</tr>
</table>
An ugly solution would be to just have 1 table cell which contains the link, then within that add another table with a table row and the other cells. So it would look like;
<tr ng-repeat="client in clients">
<a ng-href="#/user/{{client.tagid}}">
<table>
<tr>
<td>{{client.firstname}}</td>
<td>{{client.lastname}}</td>
<td>{{client.inumber}}</td>
</tr>
</table>
</a>
</tr>
I do not agree with using tables for layout!
However, you are using JavaScript and angularjs, so you would be just as good adding a click event to the table row which sends the user to the url via window.location e.g.
<tr ng-repeat="client in clients" ng-click="ChangeLocation([yoururl])">
<td>{{client.firstname}}</td>
<td>{{client.lastname}}</td>
<td>{{client.inumber}}</td>
</tr>
Then have a function within your $scope to handle this;
$scope.ChangeLocation = function(url){
window.location = url;
}
Try for this...
HTML --->
<ul ng-repeat ="item in itemList ">
<li><a data-ng-href="{{getUrl(item)}}">{{item.Name}}</a></li>
</ul>
JS --->
$scope.getUrl = function (item) {
return '/<give your path here>/' + item.ID;
};
I adapted Martin Volek's Typescript code to make an AngularJS 1.x directive:
app.directive('rowHref', function ($compile)
{
return {
restrict: 'A',
link: function (scope, element, attr)
{
scope.rowHref=attr.rowHref;
var cells = element.children("td");
angular.forEach(cells, function (cell)
{
$(cell).addClass("cell-link");
var newElem = angular.element('<a ng-href="{{ rowHref }}"></a>');
$compile(newElem)(scope);
$(cell).append(newElem);
});
}
}
});
Add his same HTML and CSS

Resources