Tuesday 15 September 2015

javascript - imagesLoaded Plugin not working with Angular JS -



javascript - imagesLoaded Plugin not working with Angular JS -

so i'm learning angularjs , i'm building little web app allows click through images randomly. click next button , image downloaded , shown, when click button goes previous image in stack.

i'd show loading spinner , disable back/forward buttons until ajax request new image complete, , image loaded

my image controller structured so:

app.controller('imagecontroller', ['imageservice', function(imageservice) { var = this; that.position = 0; that.images = []; that.loading = false; that.isloading = function() { homecoming that.loading; } that.setloading = function(isloading) { that.loading = isloading; } that.currentimage = function() { if (that.images.length > 0) { homecoming that.images[that.position]; } else { homecoming {}; } }; that.fetchskin = function() { that.setloading(true); imageservice.fetchrandomskin().success(function(data) { // info js object contains, among other things, url image want 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 notice within of that.fetchskin() function, i'm calling imagesloaded plugin when images loaded setting that.loading false. in template using ng-show show images when loading variable set false.

if set loading false outside of imagesloaded callback (like when ajax request complete) works expected, when set within of imagesloaded function template doesn't update new loading value. note console.log('images loaded'); print console 1 time images have loaded know imagesloaded plugin working correctly.

as imagesloaded callback invoked asynchronously 1 time images loaded, angular not know values of that.isloading() method calls changed. because of dirty checking angular uses provide easy utilize 2 way info binding.

if have template so: <div ng-show="isloading()"></div>

it won't update after alter values.

you need manually tell angular info changes , can done invoking $digest manually.

$scope.$digest();

just after do

console.log('images loaded'); that.setloading(false);

pseudo code can work (copied , pasted directive):

//inside controller $scope.isloading = false; // way of using imagesloaded. yours ok. $element.imagesloaded(function() { $scope.isloading = true; $scope.$digest(); });

as long alter controller $scope within async callback, there's no need phone call $apply() run $digest on $rootscope because model changes local.

javascript jquery ajax angularjs image

No comments:

Post a Comment