Issue with resizing Ionic carousel when making an $http request

In my Ionic project, I am utilizing a plugin to create a carousel (https://github.com/ksachdeva/angular-swiper). The demo of this plugin includes a simple repeat function. However, when I replaced the default repeat with my own using $http, it caused an issue where there is a delay in loading the images, leading to the slider breaking until it is resized. Here is how the HTML structure looks:

<ks-swiper-container autoplay="500" initial-slide="1" speed="5000" loop="false" show-nav-buttons="false" slides-per-view="2" space-between="20" pagination-clickable="false" override-parameters="{effect: 'coverflow',coverflow: {rotate: 0,stretch: 0,depth: 100,modifier: 1,centeredSlides: true,slideShadows : false}}" on-ready="onReadySwiper(swiper)">

            <ks-swiper-slide class="swiper-slide" ng-repeat="feature in featured track by feature.id">
                <img imageonload="" ng-src="{{feature.thumbnail_images.thumbnail.url}}" width="100%">
                <h6 ng-bind-html="feature.title"></h6>
            </ks-swiper-slide>

           <ks-swiper-slide class="swiper-slide">
            <img src="img/more.png" style="transform: rotate(180deg);" width="100%">
            <h6>Read More</h6>
            </ks-swiper-slide>

        </ks-swiper-container> 

The images are fetched from my factory using the following approach:

.controller('SwipeCtrl', function($scope, Featured) {

    $scope.swiper = {};
    $scope.onReadySwiper = function (swiper) {

        swiper.on('slideChangeStart', function () {
        });

        swiper.on('onSlideChangeEnd', function () {
        });   

    };




  $scope.featured = [];
  Featured.all().then(function (response,swiper){

      $scope.featured = response;
      for (var i =0; i < $scope.featured.length; i++) {
            $scope.featured[i].date = new Date($scope.featured[i].date);

        }
  }, 

  function (err) {
     if(window.localStorage.getItem("featured") !== undefined) {

      }
    }
  );
})

I attempted to use $timeout without success. After some research, I came across a suggestion to create a directive:

.directive('imageonload', function ($rootScope, $timeout) {
    return {
    restrict: 'A',
        link: function(scope, element, attrs) {

            element.bind('load', function() {
                $timeout(function(){
                    $rootScope.swiper.updateSlidesSize();
                });
            });


        }
    };
});

Despite implementing the directive, I consistently encounter the error "updateSlidesSize() is undefined". At this point, I'm uncertain about how to resolve this issue...

Answer №1

I encountered a similar issue recently. Upon closer inspection, I realized that the version of swiper.js I was using (not angular-swiper.js) did not contain the updateSlidesSize() function. After updating to a newer version of swiper.js, this function was included.

With that resolved, here is how I brought everything together:

//HTML snippet
<ks-swiper-container initial-slide="1" loop="false" show-nav-buttons="false" slides-per-view="3" space-between="5" pagination-clickable="false" on-ready="onReadySwiper(swiper)">...</ks-swiper-container>

//Controller logic
$scope.swiper = {}; //initialize
$scope.onReadySwiper = function (swiper)
{
  $scope.swiper = swiper; //update swiper when it's ready
};
$scope.myData=[1,2,3,4,5];
$http.jsonp(myurl+'&callback=JSON_CALLBACK').success(function(data)
{
   $scope.myData=data; //e.g.: [6,7,8]
   $timeout(function()
   {
     $scope.swiper.updateSlidesSize(); //update slide size
     $scope.swiper.slideTo(0); //go to first slide
   }, 300);
});

Please note that I have only tested this solution in Google Chrome with emulation, not on an actual mobile device.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

passing a javascript variable to html

I am facing an issue with two files, filter.html and filter.js. The file filter.html contains a div with the id "test", while the file filter.js has a variable named "finishedHTML." My objective is to inject the content of "finishedHTML" into the test div ...

Creating a cutting-edge mobile application using PhoneGap and Node.js

I have a vision to develop an app similar to a mobile messenger, but I am not a seasoned programmer. My knowledge of JavaScript is at an intermediate level, although I haven't utilized it for any significant projects. The main focus of the app would i ...

The regex string parameter in node.js is not functioning properly for matching groups

The String.prototype.replace() method documentation explains how to specify a function as a parameter. Specifying a string as a parameter The replacement string can contain special patterns for inserting matched substrings, preceding and following portion ...

Preserve multiple selected values post form submission using PHP, HTML, and JavaScript

How can I retain the selected values in a form after it is submitted? My current code functions correctly when only one value is selected, but does not maintain all selected values when multiple are chosen simultaneously. Any assistance would be apprecia ...

I'm looking for a way to securely transfer data, such as an authentication token, from a web application to an electron-based thin client. My current approach involves utilizing custom URL protocols to

Have you ever wondered how applications like Teams and Zoom produce a pop-up when clicking on a meeting link in the browser, giving you the option to continue in the browser or open in the app? When choosing to open in the app, it launches on the desktop a ...

The material-table is utilizing a component as data, but is failing to pass the component context during the onChange

I attempted to include a component as data in a material table, but I'm facing an issue with accessing the 'this' context of the component to update the state within the onChange function. Unfortunately, the editable feature offered by mater ...

Caution: An invalid next.config.js file has been detected while running the Next.js project

Whenever I try to run my project, I encounter the following three warnings: 1- warn - We found some invalid options in your next.config.js file. The property webpack5 is not recognized and may cause issues (allowed properties are: amp, analyticsId, assetP ...

What is the best way to incorporate the 'autoskip' functionality into chartjs?

Click here for an example I've been attempting to utilize the autoSkip functionality outlined in the documentation for chart.js: Visit this link for more information on autoSkip The current issue I'm facing is that my x-axis labels are o ...

Troubleshooting a JavaScript error while attempting to execute a function from a

I have been working on a new JavaScript library named TechX. Check out the code snippet below: (function(){ function tex(s){ return new tex.init(s); }; //initiate the init selector function tex.init = function(s ...

"Adding dots" in a slideshow using HTML, CSS, and JS

I'm currently working on a slideshow that includes navigation dots at the bottom. Although the slideshow is functioning properly, I am encountering an issue where only one dot appears instead of the intended three in a row. Despite my research and att ...

Why am I unable to locate my personalized module?

I've encountered an issue with my npm module not being found in my sample script after publishing it. Here is the link to my module: https://www.npmjs.com/package/kong-hmac https://github.com/y-zono/kong-hmac-js Here's what I have tried: $ m ...

When using mongoose, is it possible to add a new item and retrieve the updated array in one endpoint?

My API endpoint for the post operation query using mongoose is not returning the updated array after adding a new item. I have been struggling with this issue for 3 days without any success. Any help would be greatly appreciated. router.post("/:spot ...

Is the javascript function I created not recognized as "a function"?

A small .js file containing 3 functions for easy in-site cookie management was created. Below is the source code: // Create Cookie function Bake(name,value) { var oDate = new Date(); oDate.setYear(oDate.getFullYear()+1); var oCookie = encodeURIComponent(n ...

Display an image corresponding to the selected radio button option

Looking for guidance on implementing this in VueJS You can find a starting point here I think it involves index matching, similar to how I did it with jQuery like this: $('.Colors > li').on('mouseenter', function() { var i = ...

There seems to be an issue with the $scope value not being properly updated

In my AngularJS application, I am trying to update a $scope variable and display it in a Bootstrap modal. However, the new value is not appearing in the modal. Here is my code: View: <li ng-controller="QuickViewController"> <a href="javascri ...

How can I optimize my Javascript applications for better search engine rankings?

Recently, I've been exploring the idea of implementing a fresh workflow process for web development. Yemoan, Grunt, and Bower in conjunction with AngularJS look promising as a solution for front-end development. However, one major drawback is their po ...

center the view on the specified element

Utilizing ReactJs, I am developing a horizontal timeline that showcases dates. For instance, there is a list of 100 elements, each containing a date and text content. The dates are displayed horizontally using flex-direction="row" and overflowX ...

Using resolve to preload data in Angular's $routeProvider initialization process

I am working on an AngularJS application and need to fetch data from a REST API before the controller initializes. I am using the "resolve" in my routeProvider and have injected the necessary value into the controller to ensure that the data is available. ...

How can we eliminate all elements from jQuery except for the first and second elements?

HTML <div class="geo_select"> <h3>header 3</h3> in Above HTML code i want to remove all element except <h3> and default content<div> inside the <div class='geo_select'> in jquery.. How to remove all ...

javascriptJQuery validation function triggers JSF ajax request

I am currently experiencing a challenge with JSF ajax requests and jQuery events. I am using a jQuery event to validate a section of a form like this: jQuery(".btnNextStep").live("click", function(e) { var error = !validate(id); ... ...