Angular JS ngInfiniteScroll with LimitTo - angularjs

I'm using ngInfiniteScroll ng-module for my pagination. When i scroll down the page i'm appending 20 records to my data table. By doing that, i'm actually running a http request each time ("not good for performance).
I've been doing some research and came across adding a LimitTo with the ngInfiniteScroll. Not sure how to implement this. Could someone please give me any suggestions.
<table infinite-scroll='tF.loadMore()' infinite-scroll-disabled='tF.isBusy' infinite-scroll-distance='3' class="responsive">
<thead>
<tr>
<th>FIRST NAME</th>
<th>LAST NAME</th>
<th>USERNAME</th>
<th>EMAIL</th>
<th>CREATED DATE</th>
<th>STATUS</th>
<th>IS ONLINE</th>
<th>ACTIONS</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in tF.items | filter:searchFilter">
<td>{{item.FirstName}}</td>
<td>{{item.LastName}}</td>
<td>{{item.Username}}</td>
<td>{{item.Email}}</td>
<td>{{item.CreatedDate | date:'medium'}}</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
<tfoot ng-show='tF.isBusy'>
<tr>
<td colspan="9"><spinner show="tF.isBusy" /><span class="bold">{{tF.status}}</span> </td>
</tr>
</tfoot>
</table>
/**** CONTROLLER.JS *****/
var vm = this;
var page = 0;
vm.items = [];
vm.isBusy = false;
vm.loadMore = function ()
{
if(vm.isBusy) return;
vm.isBusy = true;
userService.GetAllRecords(page)
.success(function (data)
{
var results = data;
for (var i = 0; i < results.length; i++)
{
vm.items.push(results[i]);
}
page++;
vm.isBusy = false;
}.bind(vm))
.error(function (error)
{
vm.status = 'Error retrieving data! ' + error.message;
})
.finally(function ()
{
vm.isBusy = false;
});
}

You could load all data once, and append pieces while scrolling:
var vm = this;
var page = 0;
vm.currentItems = [];
var allData = [],
step = 10;
vm.loadData = function ()
{
userService.GetAllRecords(page)
.success(function (data)
{
allData = data;
vm.loadMore(); // Set first 10 items
})
.error(function (error)
{
vm.status = 'Error retrieving data! ' + error.message;
});
}
vm.loadMore = function () {
// Add more items to the currentItems
vm.currentItems = vm.currentItems.concat(allItems.slice(page*step, step));
page++;
}
vm.loadData();
But it depends on what you are trying to achieve why you would want this. If most of the time the users only need to see the first 10 items, then I would recommend to do a http request each time you want to load more. If a user usually scrolls through all the items, then loading all data at once may be what you want.

I've used this module myself in a few applications and this is how you would restrict the call to only running once until your data has been returned.
js code
vm.isBusy = false;
vm.loadMore = function() {
vm.isBusy = true;
userService.GetAllRecords(page).success(function(data) {
var results = data;
for (var i = 0; i < results.length; i++) {
vm.items.push(results[i]);
}
page++;
vm.isBusy = false;
});
}
template code
<div infinite-scroll="loadMore()" infinite-scroll-distance="0" infinite-scroll-disabled="isBusy"></div>
-
This is the code i wrote the last time i used this module.
<div infinite-scroll="loadMoreArticles()" infinite-scroll-distance="0" infinite-scroll-disabled="loadingArticles"></div>
$scope.loadingArticles = false;
$scope.loadMoreArticles = function() {
$scope.loadingArticles = true;
return articlesFactory.getArticles($stateParams.feedType || 'feed', $stateParams.feed, lastArticle.id).then(function(data) {
$scope.articles = _.union($scope.articles, data);
if (data.length > 0) {
$scope.loadingArticles = false;
}
});
};

Related

Here im Using AngularJs when my data in div why my total amout not counting

Here why my total amt not counting
<div ng-controller="MyHomeCNtrls">
<div id="CountdataWithinhTheDiv">
<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Quentity</td>
<td>Price</td>
<td>Total</td>
</tr>
<tr ng-repeat="pr in Prodt">
<td>{{pr.productId}}</td>
<td>{{pr.ProductName}}</td>
<td>{{pr.quantity}}</td>
<td>{{pr.Price}}</td>
<td>{{pr.Total}}</td>
<td>Total: {{ getTotal() }}</td>
</tr>
</table>
</div>
</div>
AngularCode
Service
this.Gymser = function () {
var xx = $http({ url: '/Home/Prodt', method: 'Get',params: JSON.stringify(),
content: { 'content-type': 'application/Json' } }) return xx;}
controller
function PropertyData() {
var xxx = Myservice.Gymser();
xxx.then(function (d) {
$scope.Prodt = d.data;
})
}
AngularCode For Counting
$scope.getTotal = function () {
var total = 0;for (var i = 0; i < $scope.Products.length; i++) {
var product = $scope.Products[i];total += (Product.price * Product.quantity);}return total;}
I do not see your controller having Function named getTotal()
You should have defined in the controller,
$scope.getTotal = function(type) {
var total = 0;
angular.forEach($scope.items, function(el) {
total += el[type];
});
return total;
};
DEMO

angular smart table not working

I am using smart table http://lorenzofox3.github.io/smart-table-website/ and I am trying to follow pipe/ajax plugin example. But its not showing any data. this is what I have in my html
<div ng-controller="AboutCtrl">
<table class="table" st-pipe="mc.callServer" st-table="mc.displayed">
<thead>
<tr>
<th st-sort="id">id</th>
<th st-sort="name">name</th>
<th st-sort="age">age</th>
<th st-sort="saved">saved people</th>
</tr>
<tr>
<th><input st-search="id"/></th>
<th><input st-search="name"/></th>
<th><input st-search="age"/></th>
<th><input st-search="saved"/></th>
</tr>
</thead>
<tbody ng-show="!mc.isLoading">
<tr ng-repeat="row in mc.displayed">
<td>{{row.id}}</td>
<td>{{row.name}}</td>
<td>{{row.age}}</td>
<td>{{row.saved}}</td>
</tr>
</tbody>
<tbody ng-show="mc.isLoading">
<tr>
<td colspan="4" class="text-center">Loading ... </td>
</tr>
</tbody>
<tfoot>
<tr>
<td class="text-center" st-pagination="" st-items-by-page="10" colspan="4">
</td>
</tr>
</tfoot>
</table>
</div>
and here is my js
angular.module('eventsApp')
.controller('AboutCtrl', ['Resource', function (service) {
var ctrl = this;
this.displayed = [];
this.callServer = function callServer(tableState) {
ctrl.isLoading = true;
var pagination = tableState.pagination;
var start = pagination.start || 0; // This is NOT the page number, but the index of item in the list that you want to use to display the table.
var number = pagination.number || 10; // Number of entries showed per page.
service.getPage(start, number, tableState).then(function (result) {
ctrl.displayed = result.data;
tableState.pagination.numberOfPages = result.numberOfPages;//set the number of pages so the pagination can update
ctrl.isLoading = false;
});
};
}]).factory('Resource', ['$q', '$filter', '$timeout', function ($q, $filter, $timeout) {
//this would be the service to call your server, a standard bridge between your model an $http
// the database (normally on your server)
var randomsItems = [];
function createRandomItem(id) {
var heroes = ['Batman', 'Superman', 'Robin', 'Thor', 'Hulk', 'Niki Larson', 'Stark', 'Bob Leponge'];
return {
id: id,
name: heroes[Math.floor(Math.random() * 7)],
age: Math.floor(Math.random() * 1000),
saved: Math.floor(Math.random() * 10000)
};
}
for (var i = 0; i < 1000; i++) {
randomsItems.push(createRandomItem(i));
}
//fake call to the server, normally this service would serialize table state to send it to the server (with query parameters for example) and parse the response
//in our case, it actually performs the logic which would happened in the server
function getPage(start, number, params) {
var deferred = $q.defer();
var filtered = params.search.predicateObject ? $filter('filter')(randomsItems, params.search.predicateObject) : randomsItems;
if (params.sort.predicate) {
filtered = $filter('orderBy')(filtered, params.sort.predicate, params.sort.reverse);
}
var result = filtered.slice(start, start + number);
$timeout(function () {
//note, the server passes the information about the data set size
deferred.resolve({
data: result,
numberOfPages: Math.ceil(filtered.length / number)
});
}, 1500);
return deferred.promise;
}
return {
getPage: getPage
};
}]);
and this is what my browser show
Try change this
<div ng-controller="AboutCtrl">
to
<div ng-controller="AboutCtrl as mc">
</script>-->
</script>
</script>
</script>-->
<script>
angular.module('eventsApp', ['smart-table', 'ngSanitize', 'ngRoute'])
.controller('AboutCtrl', ["$scope", "Resource", function ($scope, Resource) {
var ctrl = this;
this.displayed = Resource.GetData();
this.callServer = function callServer(tableState) {
ctrl.isLoading = true;
var pagination = tableState.pagination;
var start = pagination.start || 0; // This is NOT the page number, but the index of item in the list that you want to use to display the table.
var number = pagination.number || 10; // Number of entries showed per page.
Resource.getPage(start, number, tableState).then(function (result) {
ctrl.displayed = result.data;
tableState.pagination.numberOfPages = result.numberOfPages; //set the number of pages so the pagination can update
ctrl.isLoading = false;
});
};
} ]).factory('Resource', ['$q', '$filter', '$timeout', function ($q, $filter, $timeout) {
//this would be the service to call your server, a standard bridge between your model an $http
// the database (normally on your server)
var randomsItems = [];
function GetData() {
function createRandomItem(id) {
var heroes = ['Batman', 'Superman', 'Robin', 'Thor', 'Hulk', 'Niki Larson', 'Stark', 'Bob Leponge'];
return {
id: id,
name: heroes[Math.floor(Math.random() * 7)],
age: Math.floor(Math.random() * 1000),
saved: Math.floor(Math.random() * 10000)
};
}
for (var i = 0; i < 1000; i++) {
randomsItems.push(createRandomItem(i));
}
return randomsItems;
}
//fake call to the server, normally this service would serialize table state to send it to the server (with query parameters for example) and parse the response
//in our case, it actually performs the logic which would happened in the server
function getPage(start, number, params) {
var deferred = $q.defer();
var filtered = params.search.predicateObject ? $filter('filter')(randomsItems, params.search.predicateObject) : randomsItems;
if (params.sort.predicate) {
filtered = $filter('orderBy')(filtered, params.sort.predicate, params.sort.reverse);
}
var result = filtered.slice(start, start + number);
$timeout(function () {
//note, the server passes the information about the data set size
deferred.resolve({
data: result,
numberOfPages: Math.ceil(filtered.length / number)
});
}, 1500);
return deferred.promise;
}
return {
getPage: getPage,
GetData: GetData
};
} ]);
</script>
</head>
<body ng-app="eventsApp">
<div ng-controller="AboutCtrl as mc">
<table class="table" st-pipe="mc.callServer" st-table="mc.displayed">
<thead>
<tr>
<th st-sort="id">id</th>
<th st-sort="name">name</th>
<th st-sort="age">age</th>
<th st-sort="saved">saved people</th>
</tr>
<tr>
<th><input st-search="id"/></th>
<th><input st-search="name"/></th>
<th><input st-search="age"/></th>
<th><input st-search="saved"/></th>
</tr>
</thead>
<tbody ng-show="!isLoading">
<tr ng-repeat="row in mc.displayed">
<td>{{row.id}}</td>
<td>{{row.name}}</td>
<td>{{row.age}}</td>
<td>{{row.saved}}</td>
</tr>
</tbody>
<tbody ng-show="mc.isLoading">
<tr>
<td colspan="4" class="text-center">Loading ... </td>
</tr>
</tbody>
<tfoot>
<tr>
<td class="text-center" st-pagination="" st-items-by-page="10" colspan="4">
</td>
</tr>
</tfoot>
</table>
</div>
</body>
</html>

Display TimeSpan type Data in Angularjs Listing

Trying to show time in table but it shows me time in this format
{"Hours":16,"Minutes":8,"Seconds":45,"Milliseconds":0,"Ticks":581250000000,"Days":0,"TotalDays":0.6727430555555556,"TotalHours":16.145833333333332,"TotalMilliseconds":58125000,"TotalMinutes":968.75,"TotalSeconds":58125}
while i want it to be displayed in this format
"12:13:20"
In Html file i does listing like this
<table>
<thead>
<tr>
<th>Start Time</th>
<th>End Time</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in Festivals">
<td>{{item.StartTime}}</td>
<td>{{item.EndTime}}</td>
</tr>
</tbody>
</table>
Angular controller code where i am initializing data
var app = angular.module('myApp');
app.controller('SeasonCtrl', [
'$scope', '$http', 'seasonService', function ($scope, $http, seasonService) {
$scope.Seasons = [];
seasonService.GetAllSeasons = function () {
seasonService.getSeasons().success(function (data) {
$scope.Seasons = data.data;
})
}
seasonService.GetAllSeasons();
}
]);
C# Code i am sending data to angular controller
public JsonResult GetAllSeasons()
{
var data = _seasonManager.AllSeasons();
if (data != null)
{
var list = data.Select(r => new
{
r.StartTime,
r.EndTime
});
return Json(new { data = list }, JsonRequestBehavior.AllowGet);
}
return null;
}
I have just tried this and its solved my problem
In Html
<table>
<thead>
<tr>
<th>Start Time</th>
<th>End Time</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in Festivals">
<td ng-bind='timeFunction(item.StartTime)'></td>
<td ng-bind='timeFunction(item.EndTime)'></td>
</tr>
</tbody>
</table>
In Angular Controller
$scope.timeFunction = function (timeObj) {
var min = timeObj.Minutes < 10 ? "0" + timeObj.Minutes : timeObj.Minutes;
var sec = timeObj.Seconds < 10 ? "0" + timeObj.Seconds : timeObj.Seconds;
var hour = timeObj.Hours < 10 ? "0" + timeObj.Hours : timeObj.Hours;
return hour + ':' + min + ':' + sec;
};
This solution uses a filter and Moment.js.
In JS:
angular.module('app')
.filter('showTimeSpan', function () {
return function (timeObj, format) {
return moment(timeObj, "HH:mm").format(format);
};
});
In HTML:
<p>{{activity.startTime | showTimeSpan:"hh:mm a"}}</p>

bind dropdown and set selected value using angularJS

I have a form which populates location data, using angularJS. The form has 3 dropdowns for Location Type, Time Zone and Parent. For an existing location, I want the attributes to be selected in the dropdowns when the data is loaded. However, in following implementation, the dropdowns are populated, but the values are not selected.
HTML:
<tr>
<td style="width:20%"><label for="locationType">{{'_LocationTypeLabel_' | i18n}}:</label></td>
<td style="width:25%"><select data-ng-model="vm.locationSettings.basicSettings.locationType.locationTypeId" data-ng-options="l.locationTypeDisplayName for l in vm.locationTypes track by l.locationTypeId" /></td>
<td style="width:20%"><label for="parent">{{'_LocationParentLabel_' | i18n}}:</label></td>
<td style="width:25%"><select data-ng-model="vm.locationSettings.basicSettings.parent" data-ng-options="l.locationName for l in vm.parentLocations track by l.locationId" /></td>
</tr>
<tr>
<td style="width:20%"><label for="timezone">{{'_TimeZonesLabel_' | i18n}}:</label></td>
<td style="width:25%"><select data-ng-model="vm.locationSettings.basicSettings.timeZone" data-ng-options="l.displayName for l in vm.timeZones track by l.timeZoneId" /></td>
<td></td>
<td></td>
</tr>
controller:
function loadLocationData() {
clientcontext.clientlookup.getAllPublic().then(function (data) {
for (var i = 0; i < data.results.length; i++) {
vm.locationTypes.push(data.results[i]);
}
clientcontext.location.getLocations(vm.clientId, 1)
.then(function (data) {
for (var i = 0; i < data.length; i++) {
vm.parentLocations.push(data[i]);
}
systemcontext.systemlookup.getTimeZones()
.then(function (data) {
for (var i = 0; i < data.length; i++) {
vm.timeZones.push(data[i]);
}
//set the location attributes
vm.locationSettings.basicSettings = basicSettingsFactory.init().then(function () {
systemcontext.systemlookup.getTimeZoneById(vm.locationSettings.basicSettings.timeZone)
.then(function (data) {
vm.locationSettings.basicSettings.timeZone = data;
});
});
});
});
});
}
the location attributes are populated using a separate factory, as - vm.locationSettings.basicSettings = basicSettingsFactory.init()
function basicSettingsFactory($q, $http, $route, $location, $rootScope, $window, common, clientcontext, localize) {
var basicLocationSettings = {};
function getLocationDetails() {
clientcontext.location.getLocationById($route.current.params.clientId, $route.current.params.id)
.then(function (data) {
basicLocationSettings.id = data.locationId;
basicLocationSettings.parent = data.fkParentLocationId;
basicLocationSettings.locationType = data.locationType;
basicLocationSettings.locationName = data.locationName;
basicLocationSettings.locationDisplayName = data.locationDisplayName;
basicLocationSettings.locationCode = data.locationCode;
basicLocationSettings.isActive = data.activeStatus;
basicLocationSettings.timeZone = data.fkTimeZoneId;
});
}
return {
// Initializes the entire monitoring probe scope variables.
init: function () {
getLocationDetails();
return basicLocationSettings;
}
};
}
})();
Can someone please point out what I'm doing wrong, that doesn't set the selected value in the dropdowns?
Thanks in advance
UPDATE:
Could the issue be that, the attribute locationtype has a integer value like 3, but what's bound to the dropdown is a LocationType object?
Look your updated code, it might help you.
function basicSettingsFactory($q, $http, $route, $location, $rootScope, $window, common, clientcontext, localize) {
var basicLocationSettings = {};
// Need to put the default Ids for selection display.
//The code look like this
basicLocationSettings.id = default; //defaylt Id
function getLocationDetails() {
clientcontext.location.getLocationById($route.current.params.clientId, $route.current.params.id)
.then(function (data) {
basicLocationSettings.id = data.locationId;
basicLocationSettings.locationName = data.locationName;
basicLocationSettings.locationDisplayName = data.locationDisplayName;
});
}
return {
// Initializes the entire monitoring probe scope variables.
init: function () {
getLocationDetails();
return basicLocationSettings;
}
};
}
})();

Angularjs ui bootstrap - Don't know how to cycle through table data with Pagination

I currently have a page that has clickable data. When clicked, a modal comes up that has a table built with customer data received from a service. I have included Angularjs ui boostrap plugin and have implemented the pagination directive. I have the pagination working in the sense that the links are able to switch back and forth as well as the previous and next buttons. What I do not know how to do is cycle through the table data displaying the amount specified in the controller. Code is below:
Drilldown Directive:
var drilldownDirective = function () {
return {
restrict: 'E',
scope: {
tableData: '='
},
controller: function ($rootScope, $scope, DashboardFactory) {
var tableData = $scope.tableData;
var dashboardreportid = tableData.dashboardreportid;
var companyid = tableData.companyid;
var companybrandid = tableData.companybrandid;
var startdate = tableData.startdate;
var enddate = tableData.enddate;
var clientdb = tableData.clientdb;
var calltype = tableData.calltype;
var secondarycallval = tableData.secondarycallval;
var onSuccess = function (response) {
var d, t, dt, dtobj, obj;
var dtData = [];
$scope.repdata = [];
$scope.titles = [];
for (d in response.repdata) {
var dtArray = [];
obj = response.repdata[d];
$scope.repdata.push(obj);
//Create data packages for dataTables
for (dt in obj.data) {
dtobj = obj.data[dt];
dtArray.push(dtobj);
};
//Push data package to dtData array for injecting in dataTable
dtData.push(dtArray);
//Dynamically save field name for table headers
if (obj.ID == 0) {
var tlt = obj.data;
for (t in tlt) {
$scope.titles.push(t);
};
$scope.titles.sort();
};
};
//Pagination controls
$scope.totalItems = $scope.repdata.length;
$scope.currentPage = 1;
$scope.maxSize = 5;
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
console.log('Page changed to: ' + $scope.currentPage);
};
$scope.bigTotalItems = 175;
$scope.bigCurrentPage = 1;
};
var onError = function (response) {
console.log("error");
console.log(data);
};
DashboardFactory.getDashboardReportData(dashboardreportid, companyid, companybrandid, startdate, enddate, clientdb, calltype, secondarycallval).then(onSuccess, onError);
},
templateUrl: "dashboard/drilldownTable.html",
}
}
(directive template) drilldownTable.html
<input type='text' data-ng-model='searchbox' placeholder='search rows'></input>
<div class="table-responsive">
<table id="drilldownTable" class="table table-bordered table-condensed">
<thead>
<th data-ng-repeat="title in titles">{{title}}</th>
</thead>
<tbody>
<!-- <tr data-ng-repeat='rd in repdata | filter:searchbox | limitTo:50'> -->
<tr data-ng-repeat='rd in repdata | filter:searchbox | limitTo:bigTotalItems'>
<td data-ng-repeat='val in rd.data track by $index'>{{val}}</td>
</tr>
</tbody>
</table>
</div>
<pagination total-items="totalItems" data-ng-model="currentPage" data-ng-change="pageChanged()"></pagination>
<pre>Page: {{currentPage}} / {{maxSize}}</pre>
All help is appreciated. Thanks.

Resources