Angular Load data OnScroll - javascript

Just need some help, Im stuck and don't have an idea how to implement this append in Angular. I want to append a new data when the user scroll and the scrollbar hits the bottom. here is my code.
note DataModel.getAllData access the api with paging parameters.
I stuck on how to add new elements during onScroll. here is what i am trying to achieve on scroll I want to use the list_of_data.html. put all the new data in list_of_data. get the final output then append it on data_list.
directive
app.directive('scroll', function() {
console.log('scroll directive');
return function(scope, elm, attr) {
var raw = elm[0];
elm.bind('scroll', function() {
if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight - 20) {
scope.$apply(attr.scroll);
}
});
};
});
main.html
<div class="container" scroll="onScroll()">
<div id="data_list" data-ng-init="getData()" >
<div ng-include src="data_uri"></div>
</div>
</div>
list_of_data.html
<div ng-repeat="mydata in list_of_data">
<div>mydata.name</div>
<div>mydata.description</div>
</div>
controller
var next;
$scope.onScroll = function()
{
if(next != null || next != "undefined"){
DataModel.getAllData(user_info,next)
.then(function (data) {
$scope.list_of_data = data;
next = data.next;
}, function (error) {
console.log("error");
});
}
}
$scope.getData = function(){
$scope.data_uri= 'views/list/list_of_data.html';
DataModel.getAllData(user_info)
.then(function (data) {
$scope.list_of_data = data;
next = data.next;
}, function (error) {
console.log("error");
});
}
//EDIT I tried something like this. but it just overrides the data

You can do something like :
$scope.onScroll = function()
{
DataModel.getNextData().then(function(results){
$scope.list_of_data.push(results);
});
}
Assuming that you have a specific API function to get the next results.

Related

How can I recreate Squarespace's Product Quick View in standard Product View?

Overview
So I'm trying to take functionality from one part of Squarespace's Galapagos commerce template and add it to another but it's proving to be more difficult than I thought.
I need the image-swapping capability of the "Quick View" (example - mouse over any image and click Quick View ) to replace the column of full sized zoomable images in the "Product View" (example - you see this once you click on a product).
So I found the code for each section:
Product View
This code simply goes through each image in the array and spits it out with the id jsProductItemImages which allows it to be hovered and zoomed.
<div class="productitem-images" id="jsProductItemImages">
{.repeated section items}
{.image?}
<div class="productitem-image-zoom-wrapper sqs-image-zoom-area"><img data-load="false" class="productitem-image loading" {#|image-meta} /></div>
{.end}
{.video?}
{#|video}
{.end}
{.end}
</div>
Quick View
I'm not 100% on the logic here, but essentially it's grabbing the first image and making it a hover/zoomable primary image then listing the entire array of images beneath it as thumbnails. I read that the # symbol is the equivalent of saying this in javascript, but I don't get why it's being used to spit out only the first image in the array.
<figure class="ProductItem-gallery">
{.section items}
<div class="ProductItem-gallery-slides">
{.repeated section #}
{.image?}
<div class="ProductItem-gallery-slides-item" data-slide-index="{#index}"><img class="ProductItem-gallery-slides-item-image" data-load="false" {#|image-meta} /></div>
{.end}
{.video?}
{#|video}
{.end}
{.end}
</div>
{.end}
<div class="ProductItem-gallery-thumbnails">
{.if items.1}{.repeated section items}<div class="ProductItem-gallery-thumbnails-item"><img class="ProductItem-gallery-thumbnails-item-image" data-load="false" {#|image-meta} /></div>{.end}{.end}
</div>
</figure>
Associated JS
First off, it should be noted that I went through and console logged every function to see what was giving the Quick View it's functionality - to no avail. Which is subsequently why I'm here. So it's easy to see where the zoom function is originating: the Product View in the Galapagos.ProductItem function on line 103 $imageContainer = Y.one('#jsProductItemImages');
But I don't see anything out of the ordinary pop up when I look at the Quick View. I've got to be missing something!
var Galapagos = {};
Y.use('node', function(Y) {
Galapagos.Site = (function(){
console.log("Galapagos.Site");
var $productPage;
function init() {
console.log("Galapagos.Site init()");
$productPage = Y.one('.collection-type-products');
if( $productPage && $productPage.hasClass('view-list') ) Galapagos.ProductList.init();
if( $productPage && $productPage.hasClass('view-item') ) Galapagos.ProductItem.init();
addDesktopTouchscreenClass();
addMediaQueryBreakpointClass();
bindEventListeners();
}
function addDesktopTouchscreenClass() {
console.log("Galapagos.Site addDesktopTouchscreenClass()");
if (Y.one('html').hasClass('touch')) {
var mousemoveDetection = Y.on('mousemove', function(){
Y.one('body').addClass('galapagos-desktop-touchscreen');
mousemoveDetection.detach();
});
}
}
function addMediaQueryBreakpointClass() {
console.log("Galapagos.Site addMediaQueryBreakpointClass()");
if( document.documentElement.clientWidth <= 724 ) {
if (Y.one('.catnav-container')) Y.one('.nav-container').prepend(Y.one('.catnav-list'));
Y.one('html').addClass('tablet-breakpoint-mixin');
} else {
if (Y.one('.catnav-container')) Y.one('.catnav-container').prepend(Y.one('.catnav-list'));
Y.one('html').removeClass('tablet-breakpoint-mixin');
}
}
function bindEventListeners() {
console.log("Galapagos.Site bindEventListeners()");
Y.on('resize', addMediaQueryBreakpointClass);
}
function getDocWidth() {
console.log("Galapagos.Site getDocWidth()");
return Y.one(document).get('docWidth');
}
function getDocHeight() {
console.log("Galapagos.Site getDocHeight()");
return Y.one(document).get('docHeight');
}
return {
init:init,
getDocWidth: getDocWidth,
getDocHeight: getDocHeight
}
}());
Galapagos.TweakListener = (function(){
console.log("Galapagos.TweakListener");
function listen(tweakName, callBack) {
if (Y.Global) {
Y.Global.on('tweak:change', Y.bind(function(f){
if ((f.getName() == tweakName) && (typeof callBack === 'function')) {
callBack(f.getValue());
}
}));
}
}
return {
listen:listen
}
}());
Galapagos.ProductItem = (function(){
console.log("Galapagos.ProductItem");
var cat;
var $imageContainer;
var $images;
var imageZoomInstances = [];
function init() {
console.log("Galapagos.ProductItem init()");
cat = Y.QueryString.parse(location.search.substring(1)).category;
$imageContainer = Y.one('#jsProductItemImages');
$images = $imageContainer.all('img[data-src]');
if ( cat ) setCatCrumb();
loadProductDetailImages();
bindEventListeners();
bindTweakListeners();
buildProductDetailImagesLightbox();
}
function bindEventListeners() {
console.log("Galapagos.ProductItem bindEventListeners()");
Y.on('resize', function(){
loadProductDetailImages();
});
}
function setCatCrumb() {
console.log("Galapagos.ProductItem setCatCrumb()");
var $catCrumb = Y.one('#jsCategoryCrumb');
var $catCrumbLink = $catCrumb.one('a');
var catCrumbHref = $catCrumbLink.getAttribute('href');
//var $mobileCatCrumbLink = Y.one('#jsMobileCategoryCrumb');
$catCrumbLink.set('text', cat).setAttribute('href', catCrumbHref + '?category=' + encodeURIComponent(cat));
//$mobileCatCrumbLink.setAttribute('href', catCrumbHref + '?category=' + encodeURIComponent(cat));
$catCrumb.removeClass('galapagos-display-none');
}
function loadProductDetailImages() {
console.log("Galapagos.ProductItem loadProductDetailImages()");
var imageZoomEnabled = Y.one('.tweak-product-item-image-zoom-enabled');
$images.each(function(image) {
ImageLoader.load(image.removeAttribute('data-load'), { load:true });
if (imageZoomEnabled) {
image.on('load', function() {
instantiateImageZoom(image);
});
}
});
}
function instantiateImageZoom(image) {
console.log("Galapagos.ProductItem instantiateImageZoom()");
imageZoomInstances.push(new Y.Squarespace.ImageZoom({
host: image.get('parentNode'),
behavior: 'hover',
zoom: parseFloat(Y.Squarespace.Template.getTweakValue('tweak-product-item-image-zoom-factor'))
}));
}
function destroyImageZoomInstances() {
console.log("Galapagos.ProductItem destroyImageZoomInstances()");
if (!imageZoomInstances || imageZoomInstances.length < 1) {
return;
}
Y.Array.each(imageZoomInstances, function(zoomInstance){
zoomInstance.destroy(true);
});
}
function buildProductDetailImagesLightbox() {
console.log("Galapagos.ProductItem buildProductDetailImagesLightbox()");
if ($images.size() >= 1 ) {
var lightboxSet = [];
$images.each(function(image) {
lightboxSet.push({
content: image
});
});
// Only show controls for size > 1
var hasControls = $images.size() > 1;
$imageContainer.delegate('click', function(e) {
var lightbox = new Y.Squarespace.Lightbox2({
controls: {
previous: hasControls,
next: hasControls
},
set: lightboxSet,
currentSetIndex: $images.indexOf(e.target)
});
lightbox.render();
}, 'img', this);
}
}
function bindTweakListeners() {
console.log("Galapagos.ProductItem bindTweakListeners()");
if (Y.Global) {
Y.Global.on('tweak:close', function() {
if (Y.one('.collection-type-products.view-item')) {
destroyImageZoomInstances();
if (Y.one('.tweak-product-item-image-zoom-enabled')) {
$images.each(function(image){
instantiateImageZoom(image);
});
}
}
}, this);
}
}
return {
init:init
}
}());
Galapagos.ProductList = (function(){
console.log("Galapagos.ProductList");
var $catNav,
$productGrid,
$productGridOrphans,
$productGridImages,
$orphanProducts,
productCount,
maxGridUnit,
orphanProductCount,
isGridBuilt;
function init() {
console.log("Galapagos.ProductList init()");
$catNav = Y.one('#jsCatNav');
$productGrid = Y.one('#jsProductGrid');
$productGridOrphans = Y.one('#jsProductGridOrphans');
if (!Y.UA.mobile && Y.one('.show-alt-image-on-hover:not(.product-info-style-overlay)')) {
$productGridImages = $productGrid.all('img[data-src]');
} else {
$productGridImages = $productGrid.all('img.productlist-image--main[data-src]');
}
productCount = $productGrid.all('.productlist-item').size();
maxGridUnit = 8;
orphanProductCount;
isGridBuilt = false;
bindEventListeners();
bindTweakListeners();
if($catNav) setActiveCategory();
if(Y.one('body').hasClass('product-grid-style-organic')) {
buildGrid();
} else {
$productGrid.removeClass('loading').removeClass('loading-height');
loadGridImages($productGridImages);
}
}
function bindEventListeners() {
console.log("Galapagos.ProductList bindEventListeners()");
Y.on('resize', function(){
loadGridImages($productGridImages);
});
}
function buildGrid() {
console.log("Galapagos.ProductList buildGrid()");
for (var i = maxGridUnit; i > 0; i--) {
orphanProductCount = productCount % i;
if(productCount <= maxGridUnit || i > 4) {
if(0 === orphanProductCount) {
$productGrid.addClass('item-grid-' + i);
isGridBuilt = true;
break;
}
} else {
if(0 === productCount % 9) { // if productCount is a multiple of 9, use the 9-grid. we use 9-grid only for multiples of 9 because 8-grid looks more interesting.
$productGrid.addClass('item-grid-' + 9);
} else { // otherwise, use the 8-grid and put the remainder into the orphan div
$productGrid.addClass('item-grid-' + maxGridUnit);
$orphanProducts = Y.all('.productlist-item').slice((productCount % maxGridUnit) * -1);
$productGridOrphans
.append($orphanProducts)
.addClass('item-grid-' + productCount % maxGridUnit);
}
isGridBuilt = true;
break;
}
}
if(isGridBuilt) {
$productGrid.removeClass('loading').removeClass('loading-height');
loadGridImages();
}
}
function setActiveCategory() {
console.log("Galapagos.ProductList setActiveCategory()");
var catNavItemCount = $catNav.all('.catnav-item').size();
for (var i = catNavItemCount - 1; i > 0; i--) {
var $item = $catNav.all('.catnav-item').item(i);
var $link = $item.one('.catnav-link');
var category = Y.QueryString.parse(location.search.substring(1)).category;
var href = Y.QueryString.parse($link.getAttribute('href').substring(2)).category;
if(category && href && category === href) {
$item.addClass('active-link');
}
else if(!category) {
$catNav.one('#jsCatNavRoot').addClass('active-link');
}
}
}
function loadGridImages() {
console.log("Galapagos.ProductList loadGridImages()");
$productGridImages.each(function(image) {
ImageLoader.load(image.removeAttribute('data-load'), { load: true });
image.on('load', function(){
if (image.hasClass('productlist-image--main.has-alt-image')) {
image.siblings('.productlist-image--alt').removeClass('galapagos-hidden');
}
});
});
}
function bindTweakListeners() {
console.log("Galapagos.ProductList bindTweakListeners()");
if (Y.Global) {
Y.Global.on(['tweak:beforeopen', 'tweak:close', 'tweak:reset'], function() {
setTimeout(function(){
Galapagos.ProductList.init();
}, 1000);
});
Y.Global.on(['tweak:beforeopen'], function() {
setTimeout(function(){
Galapagos.ProductList.init();
$productGrid.one('.productlist-item').addClass('is-hovered');
}, 1000);
});
Y.Global.on(['tweak:close'], function() {
setTimeout(function(){
Galapagos.ProductList.init();
$productGrid.one('.productlist-item').removeClass('is-hovered');
}, 1000);
});
}
Galapagos.TweakListener.listen('product-grid-style', function(value) {
if('Organic' === value) {
buildGrid();
} else {
$productGrid.append($orphanProducts);
loadGridImages();
}
});
Galapagos.TweakListener.listen('product-info-style', function(value) {
if('Overlay' === value) {
$productGrid.one('.productlist-item').addClass('is-hovered');
} else {
$productGrid.one('.productlist-item').removeClass('is-hovered');
}
});
Galapagos.TweakListener.listen('productImageAspectRatio', function(value) {
loadGridImages();
});
Galapagos.TweakListener.listen('productImageSpacing', function(value) {
loadGridImages();
});
}
return {
init:init
}
}());
Y.on('domready', function() {
Galapagos.Site.init();
});
});
My Attempts
My first few attempts have been dropping the jsProductItemImages div from the Product view and dumping in the entire figure block from the Quick View then updating the associated css. While it pulls in the images (I can see them in the inspector and they take up space on the page) it shows up as being blank.
I also tried only using the thumbnails section from the Quick View and limiting the Product View to only show the first image by using {.section items.0} but then any thumbnail I clicked wouldn't swap out without writing the script for it (obviously) but I didn't want to write something like that when I know it exists in the code already!
Any help would be greatly appreciated!
UPDATE:
After replacing the product view markup with the quick view markup I ran into these errors
Uncaught TypeError: Cannot read property 'all' of null site.js:104
init # site.js:104
init # site.js:17
(anonymous function) # site.js:432
_notify # common-2a739bf…-min.js:1479
notify # common-2a739bf…-min.js:1479
_notify # common-2a739bf…-min.js:1475
_procSubs # common-2a739bf…-min.js:1476
fireSimple # common-2a739bf…-min.js:1476
_fire # common-2a739bf…-min.js:1476
fire # common-2a739bf…-min.js:1489
_load # common-2a739bf…-min.js:1463
f # common-2a739bf…-min.js:1457
Unsure why it's hitting an error with .all because it should be addressing the same array of images in both situations?
There's a few questions buried in the this post but let me answer the Quick View question specifically since that's what you're looking to "fix".
Squarespace uses a modular system of JavaScript/CSS add-ons called "rollups". If you pull the source code you'll see a window object that contains the current configuration of any given page. When visiting a Products page, the system triggers the use of their quick view JS and accommodating CSS file. This is where you'll want to be looking. The JS you're digging into is not relevant to Quick View (I don't believe).
Quick View Rollup JS: http://static.squarespace.com/universal/scripts-compressed/product-quick-view-6a1e5642b473ebbb5944-min.js
Quick View Rollup CSS: http://static.squarespace.com/universal/styles-compressed/product-quick-view-eb4b900ac0155bed2f175aa82e2a7c17-min.css
These rollups are triggered off of JavaScript hooks in the template files. What you'll need to do is experiment with using the Galapagos product template word and word so it has the same classes and data-attributes, and see if that works. It would take far too long to cover all of the details of what you need to do without actually working on the project. I would start here first and see if you can setup your product template to triggers the Quick View JS as is, without customization.

pre-fetch in AngularJS when view is loaded

I have an angularJS application whit infinite scrolling: this means every time I reach the bottom of the page a new ajax call happens.
I simply want to check when the page is fully loaded, every time an ajax call happens. If I'm able to check if the page is loaded I can pre-fetch the json for next page.
window.onload works only for static pages, and $scope.on/watch('$viewContentLoaded', function() {}) is fired as the first thing when I do an ajax call. I mean: it is fired and after that I can see the items of the ajax call. It should be fired as the last thing, when the page is loaded.
$scope.nextPage = function() {
$http.jsonp(url).success(function(response) {
console.log(response.data);
}
$scope.$watch('$viewContentLoaded', function() {
console.log("page is loaded");
});
}
Ok guys, thanks for help. I've developed the solution and it's working fine.
As usual, for me, AngularJS doc is very clear: it does says nothing, or it's a messy.
I've used ngInfiniteScroll plugin combined with the relative Reddit demo
Just a question: what do you think about how I've used $q? It's not nice for me. I mean I defined interval just to use $q.
HTML
<div ng-app='myApp' ng-controller='DemoController'>
<div infinite-scroll='nextPage()' infinite-scroll-disabled='busy' infinite-scroll-distance='1'>
<div ng-repeat='item in items'>
<span class='score'>{{item.score}}</span>
<span class='title'>
<a ng-href='{{item.url}}' target='_blank'>{{item.title}}</a>
</span>
<small>by {{item.author}} -
<a ng-href='http://reddit.com{{item.permalink}}' target='_blank'>{{item.num_comments}} comments</a>
</small>
<div style='clear: both;'></div>
</div>
<div ng-show='reddit.busy'>Loading ...</div>
</div>
</div>
JS
var myApp = angular.module('myApp', ['infinite-scroll']);
myApp.service('ajaxcall', function($http) {
this.getjson = function (url) {
return $http.jsonp(url).success(function(response) {
console.log('inside service ' + response.data.children);
return response;
});
}
});
myApp.controller('DemoController', function(ajaxcall, $scope, $q) {
$scope.busy = false;
$scope.items = [];
var after = '';
var prefetch = false;
var get_items;
$scope.nextPage = function() {
if ($scope.busy) return;
$scope.busy = true;
if (!prefetch) {
prefetch = true;
get_items = ajaxcall.getjson("https://api.reddit.com/hot?after=" + after + "&jsonp=JSON_CALLBACK");
}
interval = $q.when(get_items).then(function(data) {
if (get_items) {
console.log(data);
var new_items = data.data.data.children;
for (var i = 0; i < new_items.length; i++) {
$scope.items.push(new_items[i].data);
}
after = "t3_" + $scope.items[$scope.items.length - 1].id;
get_items = ajaxcall.getjson("https://api.reddit.com/hot?after=" + after + "&jsonp=JSON_CALLBACK");
$scope.busy = false;
}
})
};
});

How to check if all documents are loaded with Firebase.util pagination

How can I check if I have to stop calling the loadMore() function, because all the documents have already been loaded from the database?
In the example below I'm using Ionic, but it's the same also with ng-infinite-scroll in AngularJS apps.
This is my actual code:
HTML:
...
<ion-infinite-scroll
ng-if="!noMoreItemsToLoad"
on-infinite="loadMore()"
distance="5%">
</ion-infinite-scroll>
</ion-content>
JS Controller:
$scope.loadMore = function(){
console.log('Loading more docs...');
Items.loadMore(); // calling the .next() method inside the Items service
if( !Items.hasNext()) { $scope.noMoreItemsToLoad = true; }
$scope.$broadcast('scroll.infiniteScrollComplete');
}
JS Items Factory:
.factory('Items', function (FIREBASE_URL, $firebaseArray, $firebaseObject) {
var itemsRef = new Firebase(FIREBASE_URL + 'items/');
var scrollRef = new Firebase.util.Scroll(itemsRef, 'name');
var self = {
getAllItems : function(){ ... },
loadMore: function(){
scrollRef.scroll.next(4);
},
hasNext: function(){
if(scrollRef.scroll.hasNext()) { return true; }
else { return false; }
}
}
return self;
}
Do the scroll.next in timeout, for example:
loadMore: function(){
$timeout(function() {
scrollRef.scroll.next(4);
});
},
I had the same issue and I think the solution is to modify the hasNext() function on firebase.util.js:
Cache.prototype.hasNext = function() {
return this.count === -1 || this.endCount >= this.start + this.count;
};
I put a missing equal sign (=) before this.start
I hope it works for you.

KnockoutJs - How to throttle the binding afterkeydown

I got this working for my filtering functionality.
<input data-bind="value: filterByName, valueUpdate:'afterkeydown'" />
<div data-bind="foreach: filteredRecords"/>
</body>
Now i just need to throttle the binding of the filteredRecords or to put delay on it
my view model looks like this
self.filteredRecords= ko.computed(function () {
return getRecordByStatus(1);
});
self.filterByName= ko.observable("");
var getRecordByStatus = function (status) {
var periodRecord, filtered = [];
if (self.timesheetApprovalResponse().periods) {
// period filtering
if (self.selectedPeriod()) {
periodRecord = _.find(self.timesheetApprovalResponse().periods, function(p) {
return p.fromDate === self.selectedPeriod().key;
});
if (periodRecord) {
filtered = _.where(periodRecord.timesheets,
function(t) {
return t.status === status;
});
}
}
}
if (self.filterByName()) {
filtered = _.where(filtered,
function (t) {
console.log(t.name.toLowerCase() + "-" + self.filterByName().toLowerCase());
return t.name.toLowerCase().indexOf(self.filterByName().toLowerCase()) > -1;
});
}
return filtered;
};
Now my problem is where to put the .extend({ throttle: 500 });
I think I cannot put it on filteredRecords as it will also throttle in Page Load ?
Any other ideas?
If I understand what you are after, then you probably want to throttle filterByName. This will prevent filteredRecords from being notified until filterByName stops changing for x milliseconds.

Spine.js Unknown Record (possible scope error?)

If I have a list of "albums," and I click on one, I navigate to another view (/#/album/:id) which is controlled by a controller called SingleAlbum. It fetches the data correctly, but I can't get it to render. I've looked over other 'Unknown Record' issues on SO and on the Spine Google Group, but no dice. Here's my code:
var SingleAlbum = Spine.Controller.sub({
apiObj: {
url: '/api/album',
processData: true,
data: {
id: ''
}
},
model: Album,
panel: $('.album_single'),
tmpl: $('#albumTpl'),
init: function() {
this.apiObj.url = this.model.url;
if(this.panel.children.length > 0) {
this.panel.html('');
}
},
render: function(id) {
console.log('render');
var template = singleAlbum.tmpl.html(),
data = Album.find(id), // <-- this doesn't want to work
html = Mustache.to_html(template, data);
singleAlbum.panel.html(html);
},
getData: function(id) {
//var me = this;
console.log('get data');
this.apiObj.data.id = id;
this.apiObj.url = this.model.url;
this.model.bind('refresh change', function(id) {
//me.render(id);
singleAlbum.render(id);
console.log('should be rendered');
});
this.model.fetch(this.apiObj);
console.log('record: ',this.model.find(id));
if(Object.keys(this.model.find(id)).length > 0) {
//this.render(id);
}
}
});
The problem happens when I call .render() on the event handler. I can manually see that Album.all() has records, and can do Album.find(id) anywhere else in the app, but when I do it on var data = Album.find(id) it fails. Is this a scope issue? Am I missing something obvious?
By the by, please excuse the verboseness of my code. I'm actually making a SingleItem controller, of which SingleArtist and SingleAlbum will be subclasses. I thought that might be an issue, so I ripped out the code to test it on it's own.
EDIT: Specifically, my route looks like this:
'/album/:id': function(params) {
console.log('navigated to /album/', params.id);
singleAlbum.getData(params.id);
}
Aha! I was passing id in my event handler, which was overwriting the other id variable. Here's what it should look like:
render: function(id) {
var template = this.tmpl.html(),
data = this.model.find(id),
html = Mustache.to_html(template, data);
this.panel.html(html);
},
getData: function(id) {
var me = this;
this.apiObj.data.id = id;
this.apiObj.url = this.model.url;
this.model.bind('refresh change', function() { // <-- don't need to pass anything
me.render(id);
});
this.model.fetch(this.apiObj);
}

Categories