imagesLoaded Plugin not working with Angular JS - javascript

So i'm learning AngularJS and i'm building a small web app that allows you to click through images randomly. Basically you click the next button and an image is downloaded and shown, when you click the back button it goes to the previous image in the stack.
I'd like to show a loading spinner and disable the back/forward buttons until the ajax request for the new image is complete, AND the image is completely loaded
My image controller is structured like so:
app.controller('ImageController', ['imageService', function(imageService) {
var that = this;
that.position = 0;
that.images = [];
that.loading = false;
that.isLoading = function() {
return that.loading;
}
that.setLoading = function(isLoading) {
that.loading = isLoading;
}
that.currentImage = function() {
if (that.images.length > 0) {
return that.images[that.position];
} else {
return {};
}
};
that.fetchSkin = function() {
that.setLoading(true);
imageService.fetchRandomSkin().success(function(data) {
// data is just a js object that contains, among other things, the URL for the image I want to display.
that.images.push(data);
that.imagesLoaded = imagesLoaded('.skin-preview-wrapper', function() {
console.log('images loaded');
that.setLoading(false);
});
});
};
that.nextImage = function() {
that.position++;
if (that.position === that.images.length) {
that.fetchSkin();
}
};
that.previousImage = function() {
if (that.position > 0) {
that.position--;
}
};
that.fetchSkin();
}]);
If you notice inside of the that.fetchSkin() function, i'm calling the imagesLoaded plugin then when the images are loaded I am setting that.loading to false. In my template I am using ng-show to show the images when the loading variable is set to false.
If I set loading to false outside of the imagesLoaded callback (like when the ajax request is complete) then everything works as expected, when I set it inside of the imagesLoaded function the template doesn't update with the new loading value. Note that the console.log('images loaded'); does print to the console once the images have loaded so I know the imagesLoaded plugin is working correctly.

As your imagesLoaded callback is invoked asynchronously once images are loaded, Angular does not know that values of that.isLoading() method calls changed. It is because of dirty checking that Angular uses to provide you with easy to use 2 way data binding.
If you have a template like so:
<div ng-show="isLoading()"></div>
it won't update after you change the values.
You need to manually tell angular about data changes and that can be done by invoking $digest manually.
$scope.$digest();
just after you do
console.log('images loaded');
that.setLoading(false);
Pseudo code that can work (copied and pasted from my directive):
//inside your controller
$scope.isLoading = false;
// just another way of using imagesLoaded. Yours is ok.
$element.imagesLoaded(function() {
$scope.isLoading = true;
$scope.$digest();
});
As long as you only change your controller $scope within async callback, there's no need to call $apply() to run $digest on $rootScope because your model changes are only local.

Related

JQuery $.post callback firing a function that never finishes

Here's the problem. I'm making a callback to the server that receives an MVC partial page. It's been working great, it calls the success function and all that. However, I'm calling a function after which iterates through specific elements:
$(".tool-fields.in div.collapse, .common-fields div.collapse").each(...)
Inside this, I'm checking for a specific attribute (custom one using data-) which is also working great; however; the iterator never finishes. No error messages are given, the program doesn't hold up. It just quits.
Here's the function with the iterator
function HideShow() {
$(".tool-fields.in div.collapse, .common-fields div.collapse").each(function () {
if (IsDataYesNoHide(this)) {
$(this).collapse("show");
}
else
$(this).collapse("hide");
});
alert("test");
}
Here's the function called in that, "IsDataYesNoHide":
function IsDataYesNoHide(element) {
var $element = $(element);
var datayesnohide = $element.attr("data-yes-no-hide");
if (datayesnohide !== undefined) {
var array = datayesnohide.split(";");
var returnAnswer = true;
for (var i in array) {
var answer = array[i].split("=")[1];
returnAnswer = returnAnswer && (answer.toLowerCase() === "true");
}
return returnAnswer;
}
else {
return false;
}
}
This is the way the attribute appears
data-yes-no-hide="pKanban_Val=true;pTwoBoxSystem_Val=true;"
EDIT: Per request, here is the jquery $.post
$.post(path + conPath + '/GrabDetails', $.param({ data: dataArr }, true), function (data) {
ToggleLoader(false); //Page load finished so the spinner should stop
if (data !== "") { //if we got anything back of if there wasn't a ghost record
$container.find(".container").first().append(data); //add the content
var $changes = $("#Changes"); //grab the changes
var $details = $("#details"); //grab the current
SplitPage($container, $details, $changes); //Just CSS changes
MoveApproveReject($changes); //Moves buttons to the left of the screen
MarkAsDifferent($changes, $details) //Adds the data- attribute and colors differences
}
else {
$(".Details .modal-content").removeClass("extra-wide"); //Normal page
$(".Details input[type=radio]").each(function () {
CheckOptionalFields(this);
});
}
HideShow(); //Hide or show fields by business logic
});
For a while, I thought the jquery collapse was breaking, but putting the simple alert('test') showed me what was happening. It just was never finishing.
Are there specific lengths of time a callback function can be called from a jquery postback? I'm loading everything in modal views which would indicate "oh maybe jquery is included twice", but I've already had that problem for other things and have made sure that it only ever includes once. As in the include is only once in the entire app and the layout is only applied to the main page.
I'm open to any possibilities.
Thanks!
~Brandon
Found the problem. I had a variable that was sometimes being set as undefined cause it to silently crash. I have no idea why there was no error message.

Prevent calling ajax on scroll when already called

I have a plugin that tells me if an element is visible in the viewport with $('#element').visible() (set to true when visible).
Now I want to create a function that I scroll down a page and load new content with ajax. I have this so far:
window.onscroll = function() {
console.log($('#ele').visible());
if ($('#ele').visible()) {
//ajax call comes here
}
};
As soon as I see the element my log shows true:
I don't have problems implementing the ajax-request now, but shouldn't I block this function to occur only once? How could I prevent that a new element that already has been loaded to load again (prevent using ajax again)?
I thought of using a boolean-variable, but my problem is that I don't know how to implement that because if I set a variable, how would the browser know it's value? Because on every move of my mousewheel it cant remember what that variable's value was?
EDIT:
I tried the code of Ismail and it never reaches the ajax call (alert won't show).
window.onscroll = function() {
var ajaxExecuted = false;
var ele = $('#load_more').visible();
console.log(ele);
return function() {
if (ajaxExecuted) return;
if (ele) {
alert("OK");
var ajaxArray;
ajaxArray = { page: 2 }
ajaxLoadContent(ajaxArray, "load_more", "ajax_load");
ajaxExecuted = true;
}
}
};
You can use this:
window.onscroll = (function() {
var ajaxExecuted = false;
return function() {
if(ajaxExecuted) return;
if ($('#ele').visible()) {
$.ajax({...}).success(function() {
//Your code here;
ajaxExecuted = true;
});
}
}
})();
One easy solution: set a boolean to true when the element first becomes visible and set it to false when it stops being visible. Only fire the request if those states mismatch (i.e. if it's visible but the boolean is false - that means it's the first time you've seen the window. You'd then set the bool afterwards so it won't fire off anymore until it disappears and reappears again).

AngularJS service is not updating the view

I have a service declared in my application.js file within my AngularJS project. It looks like this:
application.factory('interfaceService', function ($rootScope, $timeout) {
var interfaceService = {};
interfaceService.lang = "";
interfaceService.dev = ""
interfaceService.theme = "";
interfaceService.integ = "";
//For Integration Type
interfaceService.demo = function (dev, theme, integ, lang) {
this.dev = dev;
this.theme = theme;
this.integ= integ;
this.lang = lang;
this.broadcastItem();
};
interfaceService.broadcastItem = function () {
$timeout(function(){
$rootScope.$broadcast('handleBroadcast');
});
};
return interfaceService;
});
I am using the above service to pass variables between 2 of my Controllers. The controller which calls the service is here:
$scope.buildDemo = function () {
interfaceService.demo(device, template, integ, language);
$rootScope.template = template;
$rootScope.themeFolder = template;
$state.go("MainPage", {
"themeName": $rootScope.themeFolder
});
}
That function is triggered when the user clicks on a div on my view
<div id='build-btn' ng-click='buildDemo()'>Go</div>
The problem I am having is that my view is not updating when I click on the button. I have to click on it a second time to see any changes. Would anyone know what is causing this? The URL updates and the new view comes onto the page but the elements that should be showing based on the parameters set in the service are not visible until I click on the "Go" button a second time.
On first click handleBroadcast event gets broadcasted and but haven't received by anyone, because when you press "GO" button, at that time state transition occurs and it loads template and its controller. When controller instantiated, it register the listener event using $on on handleBroadcast event.
I'd suggest you that to wait to broadcast an event till controller & its underlying view gets render. This can be done by taking advantage of promise returned by $state.go method. Which completes when transition succeeds.
Code
$scope.buildDemo = function() {
//state transition started.
$state.go("MainPage", {
"themeName": $rootScope.themeFolder
}).then(function() {
//state transition completed
//controller instance is available & listener is ready to listen
interfaceService.demo(device, template, integ, language);
$rootScope.template = template;
$rootScope.themeFolder = template;
});
}

Javascript & Soundcloud Widget: How to load new track into SC Widget iFrame (via URL)

I’ve seen different web apps like Playmoss, Whyd, and Songdrop etc. that, I believe, HAVE to utilize the Soundcloud Embedded Widget in order to produce the functionality of playing multiple tracks, in sucession, not apart of a set/(playlist). Currently I am having issues reproducing this functionality with the following library, so I decided to attempt to write my own:
https://github.com/eric-robinson/SCLPlayer
I am very new to writing javascript, but my below code, will load a first track, and play it once hitting the “ready” bind. Once hitting the “finish” bind, It will then jump to the loadNextTrack() function and load the next tracks URL, into the src of the widget’s iFrame. After that, it doesn’t ever hit the original “ready” bind, which would then begin playback.
So to clear things up, playback doesn’t begin for the second track.
<script type = "text/javascript">
var SCLPlayer = {
isPlayerLoaded : false,
isPlayerFullLoaded : false,
needsFirstTrackSkip : true,
isPaused: true,
scPlayer : function() {
widgetContainer = document.getElementById('sc');
widget = SC.Widget(widgetContainer);
return widget;
},
loadNextTrack : function() {
var ifr = document.getElementById('sc');
ifr.src = 'http://w.soundcloud.com/player/?url=https://api.soundcloud.com/tracks/231758952';
console.log ('Loading Next Track');
SCLPlayer.scPlayer().bind(SC.Widget.Events.READY, function() {
console.log ('Player is Ready, next Track');
SCLPlayer.scPlayer().play();
});
}
};
$( '#sc' ).ready(function() {
SCLPlayer.scPlayer().bind(SC.Widget.Events.READY, function() {
SCLPlayer.isPlayerLoaded = true;
//window.location = 'sclplayer://didLoad';
console.log ('Player is Ready');
SCLPlayer.scPlayer().play();
});
SCLPlayer.scPlayer().bind(SC.Widget.Events.PLAY, function() {
SCLPlayer.isPaused = false;
//window.location = 'sclplayer://didPlay';
console.log ('Player did Play');
});
SCLPlayer.scPlayer().bind(SC.Widget.Events.PAUSE, function() {
SCLPlayer.isPaused = true;
//window.location = 'sclplayer://didPause';
console.log ('Player did Pause');
});
SCLPlayer.scPlayer().bind(SC.Widget.Events.FINISH, function() {
SCLPlayer.isPaused = true;
//window.location = 'sclplayer://didFinish';
console.log ('Player did Finish');
SCLPlayer.loadNextTrack();
});
});
</script>
</head>
<body>
<iframe id = "sc" width="100%" height="100%" scrolling="no" frameborder="no" src="http://w.soundcloud.com/player/?url=https://api.soundcloud.com/tracks/226183306"></iframe>
</body>
The whole point of me writing this Javascript is so that I can then use a Swift to Javascript bridge in my iOS app to then control the loading of tracks into the embedded players. For some reason over a slower connection, the next track doesn't always load into the player, using the "bridge". I hope to provide the nextTrackURL to the javascript side of things before the currentTrack finishes, so that the bridge conveys nothing and the Javascript handles new track loading, solely on its own.
I think you want to use the load function to specify the url for the new track
From the soundcloud Widget API docs:
load(url, options) — reloads the iframe element with a new widget specified by the url. All previously added event listeners will continue working. options is an object which allows you to define all possible widget parameters as well as a callback function which will be executed as soon as new widget is ready. See below for detailed list of widget parameters.
var url = "https://api.soundcloud.com/";
var options = [];
// if a track
url += "tracks/";
// if a playlist
url += "playlists/"
// append the id of the track / playlist to the url
url += id;
// set any options you want for the player
options.show_artwork = false;
options.liking = false;
options.auto_play = true;
widget.load(url, options, OPTIONAL_CALLBACK_FUNCTION);
Edited to show binding...
The bind code is called once, after the widget is initially loaded.
The ready event is only called once, when the widget is initially loaded, it is not called for each subsequent call using load().
try {
widget.bind(SC.Widget.Events.FINISH,
function finishedPlaying() {
// your code / function call
}
);
widget.bind(SC.Widget.Events.PAUSE,
function paused() {
// your code / function call
}
);
widget.bind(SC.Widget.Events.PLAY,
function playing() {
// your code / function call
widget.getCurrentSound(function scCurrentSound(sound) {
// this also binds getCurrent sound which is called
// each time a new sound is loaded
});
}
);
widget.bind(SC.Widget.Events.PLAY_PROGRESS,
function position(pos) {
// your code / function call
}
);
widget.bind(SC.Widget.Events.SEEK,
function seek(pos) {
// your code / function call
}
);
widget.bind(SC.Widget.Events.READY,
function ready() {
// your code / function call
}
);
} catch(e) {
// exception handler code
}

Pagedown editor attach handler to image dialog

I've made my own upload library dialog with Semantic UI's modal. I'm trying to integrate this dialog within the Pagedown editor.
var converter = Markdown.getSanitizingConverter();
var editor = new Markdown.Editor(converter);
editor.hooks.set("insertImageDialog", function(callback) {
uploadModal.load(); // The dialog HTML gets loaded asynchronously
$('body').on('selection', '.upload-modal', function(e, src) {
console.log(src);
callback(src);
});
return true; // tell the editor that we'll take care of getting the image url
});
Everything works fine the first time selecting an image from the dialog, but after that it breaks:
Uncaught TypeError: Cannot call method 'removeChild' of null Markdown.Editor.js
According to this SO question it has something to do with defining the event handler multiple times, but I can't wrap my head around it.
Some more info:
The HTML for initializing the modal is loaded asynchronously, here is the JS code:
var uploadModal = (function() {
/**
* Load the upload modal.
*/
this.load = function() {
var $modal = $('.upload-modal');
if ($modal.length) {
// Show the already existing modal.
$modal.modal('show');
} else {
// Get the HTML
var request = $.get(appUrl('admin/upload/modal'));
request.done(function(html) {
// Make the modal.
var $modal = $(html);
$modal.modal({
observeChanges: true,
onApprove: function () {
var upload = $modal.find('.selected.upload'),
src = upload.find('.image > img').attr('src');
// Bind the event listener which will return the upload's source URL
$modal.trigger('selection', src);
return true;
}
}).modal('show');
// Some event handlers here
});
}
};
})();
I load the modal by calling uploadModal.load() and watch whenever an image is selected by attaching the 'selection' event handler.

Categories