Make A Gallery-Like Image Grid Using Ionic Framework

I recently started making an application with Ionic Framework that made heavy use of images both remotely and locally.  During this time, my goal was to present the images in a grid that looks good for all device sizes and orientations.

One might think this would be an easy task because Ionic offers both grids and a responsive class, however, trivial was far from the case.  Instead I had to go to my programming roots and create some display logic when looping through my arrays of images.  The following guide will show exactly what I had to do.

My goal was to create an image grid that looked like the following:

Ionic Image Grid

It wasn’t so simple though.  To demonstrate what I’m talking about, let’s go through the process of creating a fresh Ionic Android and iOS project:

Remember, if you’re not using a Mac, you cannot add and build for the iOS platform.

At this point we don’t need any additional libraries or plugins.  We will be using pure CSS and JavaScript.

To start, we’re going to go through a pretty vanilla scenario where we use the CSS resources provided from the Ionic Framework documentation.  Open your project’s www/js/app.js file and make it look something like this:

The above JavaScript code will be used in each of our two scenarios.  It is very basic in the sense that we are loading 100 generic images into an array that we’ll eventually loop through.

Now in your www/index.html file let’s check out the responsive class for grids:

Based on the above code, one would hope that only four columns appear on the screen and the rest would float below because we set each column to 25%.  This is not the case.  Instead four images appear on the screen when the screen is large and only when the screen becomes small do the images stack.  However, when the images stack it becomes one image per row rather than the four images per row that we had hoped for.

This is where we are going to jump in with some beautiful AngularJS code.

Back in your www/index.html code, edit the <ion-content> tags to contain the following:

Notice in the above code we are doing the following:

  1. When we are on every forth image, we are going to show the row class, thus creating a new row
  2. We pre-allocate four columns for our row, but we first check to see if it will ever be filled to prevent an undefined exception
  3. If the image exists at the specified index, then add it to the column

Just like that we have many rows with four images per row.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • nice one, wished if you added some lightbox to it cause this is what cause the most pain in building such app ( I guess ) 😉

    thanks

    • Who says such a tutorial isn’t coming 😉

      • am waiting for it since ages 😉

        thanks man for your huge effort to explain things to everyone out there

  • Barry Mc Gettigan

    Looks fantastic. Thanks for the tutorials 🙂

  • Oak Krittee

    Thanks for the tutorials. This tutorial support for huge lists of items?

    • Depends what you consider to be a huge list. I’ve tried with a list of 100 items and it works fine.

      I can’t say I recommend doing that long term though. Long term you should probably consider adding paging or an infinite scroll.

      Regards,

  • Thanks for this. I was actually busy doing the same, but now I dont need to anymore 🙂

    • I’m glad you benefited from it 🙂

  • Edward Soares

    Is there anyway to make something like this work for list card? I have tried reworking this code for list card with no luck, i am using ng-repeat item in items etc. I am trying to find a way to show 2 to 3 wide on tablet and 1 wide on phone with no luck.

    • I’m not sure I understand. You want a card that has a grid of images or a grid of cards?

      Regards,

      • Edward Soares

        A grid of cards, I have since achieved it using css with borders and spacing etc, looks rather nice actually so I think im satisfied with it. I think I would still like to see an example though if it possible. I an also share the css if wanted, it seems ionics grid responsive does not kick cards below as screen gets smaller so had to force it to do it with the css.

        • I think the only way to do that is with a bunch of media queries for each of the screen resolutions you wish to support. Not fun if CSS isn’t your favorite thing to write, but until Ionic starts supporting multi-resolution displays, I think it is the only option.

          • Edward Soares

            Yeah i think your right on that, thats exactly what im doing now. css is one of my strong points so im finding it relatively easy to make it work with css. thank you for your quick responses.

          • Sorry I couldn’t be of more help on this one.

          • Edward Soares

            Plenty of help, all of your blogs as well.

  • Steve OConnor

    Another option worth a try is to use the wonders of flexbox to handle consistent wrapping of widgets. Given that ionic is built on top of flexbox, this can be quite easy to pull off in many situations. It wont give you the fine control of having an exact number of cols, as per Nic’s demonstration above, but it will cope with a lot of the situations mentioned in the reader questions below.

    example – declare a class for wrappable content in your .css file, lets call it gallery :

    Now apply the gallery class to the div container that you want to apply wrapping in …

    The spans are all chucked together on the same line, but flexbox will automatically wrap them over several lines in a clean and responsive way, depending on the width of the device. This works a treat inside a card list, inside an ion-item, or anything really !

    This is not exactly the same as what Nic is doing above … but it might be a solution for some readers. I found it really helpful to know that flexbox exists under the surface of ionic, and can be incredibly useful at times.

    More info on flexbox here :
    https://css-tricks.com/snippets/css/a-guide-to-flexbox/

    • I wasn’t aware of this, so thanks a ton for sharing! I know it will help others looking for an alternative to what I’ve done.

      Regards,

      • Steve OConnor

        Thanks Nic. I only found this by accident .. its not clearly stated in the ionic docs, as far as I can see. (probably buried somewhere in the docs)

        Its got some cool features too, and looks like it is built to handle the worst scenarios that developers can throw at it.

        I have one section in my app that for highly esoteric reasons, needs to render avatars on a row from right to left. This is impossibly difficult using regular coding tricks, but is trivial with flexbox.

        Was a good find for sure 😉

        • Adilson Ferreira

          Some Android devices doesn’t work properly =/

      • Gobinath Sekar

        hi Nic,
        how to Order the contents of an array of images ?

        • You’d probably have to use an object instead of an array and then assign some kind of priority or value to sort on.

          Regards,

    • Gustavo Reyes

      Hey Nic,

      I’m trying to figure out how to filter using this technique. Any ideas?

      So far I’ve tried like this:

      ng-hide=”projectCollection[$index].category != filterCategory.category.id”

  • Adilson Ferreira

    How does it work with filter? If I have a list of images and image name…

    • Can you give me an example of what you’re trying to accomplish?

      • Adilson Ferreira

        Just try to filter via input some images from your gallery, you’ll see the problem. I’ve already tried this method before, but the filter doesn’t recognise columns individually.

        I want to build a gallery like yours, but I have image and description. At the top of the gallery I need to create a input to filter the images by description.

        • Before I try to get you some code, can you please share what you’ve already tried? Maybe put your project on GitHub for me.

          Regards,

          • reptilian_brain

            Hi, i tried this filter approach, here is the code

            http://pastebin.com/iqrAGmr5

            Would appreciate your input on how to improve this.

            Sorry for not posting a github version, it’s difficult to tear the part out of the project at this point.I hope you will see the idea there and why it does not work.

  • Guest

    I want to build a gallery like yours, but I have image and description. At the top of the gallery I need to create a input to filter the images by description.

    I’ve already tried this method before, but the filter doesn’t recognise columns individually.

    Just try to filter via input some images from your gallery, you’ll see the problem.

  • Mhabub

    Hi
    thanks for nice post.
    If i want to show one item in first row with 100% width and in second row 2 items with 50% – 50% width.
    how should I set logic in <div class=”row” ?

    • This is a little off topic from what I was trying to prove.

      You would have to use your own logic for determining which row / column would receive which treatment.

      Regards,

  • Web Talk

    Thank you so much…You rock !!!. I was having issues in getting $index, later found was referring to image[$index] instead of images[$index]

  • wilsonfpz

    Hi, thanks a lot. is it possible to extends the tutorial and makes it a switchable grid(gird and list) like this one,http://tutorialzine.com/2013/08/learn-angularjs-5-examples/ ? The user can change the view layout. thanks!

    • That is an entirely different topic. I may consider a tutorial in the future, but this current tutorial serves a different purpose.

      Thanks for the suggestion!

      • wilsonfpz

        Hi, thanks for you post.
        I tried myself to make the switchable layout.And it almost done.
        http://codepen.io/WilsonFpz/pen/jPYqBq

        But there is one problem, I can not make the these two layout sync.

        For example, when user scroll to the last item(99) in the list layout, then switch to the grid,
        the first item is about (76).
        Could you give me some trick about how to sync roughly for these two layouts?
        Thanks.

        • Your CodePen doesn’t demonstrate what you’re trying to do. I just see an image grid.

          Switchable layouts is best saved for a different tutorial. You may want to post in the forums if you’re in a hurry.

          Regards,

  • Andrew Saul

    Anyway to make the images go full width?

    • You mean take up the full screen of the device? That is beyond the point of this tutorial if that is what you are referring to.

      The grid is what I was trying to demonstrate.

      Regards,

      • Andrew Saul

        I can’t get the padding around the images to go away. I’d like to have no margin around the images, but for some reason when I remove the padding I am left with a weird gutter on the right side. Any ideas?

        • Can you attach a screenshot to the comments so I get a better idea?

  • Matt

    Hi Nic,
    Is there a way to make images the same size if i’m using multiple images in the grid?

    • You’d have to do some CSS wizardry to center crop the image into a fixed dimension space

      • Matt

        Thanks for you response,

        I have created some css code which center crops an image. http://jsfiddle.net/vYdBt/452/.

        How would i scale the image in ionic? I can’t use px because wouldn’t the sizing look different on individual devices?

        How would i use %?

        • Media queries are going to be the only way to make it pixel perfect.

  • NIsham Mahsin

    can i use cards for making gallery like icon grids
    as

    how to use multiple cards in a row?

    • I don’t see why not. Just mess around with your CSS.

  • Sivaneswary Sukumaran

    Nice post.saved lot of my time.

  • Gobinath Sekar

    Yeah this is nice,but how to sort of this content.Because here mentioned $index

  • Eyy Nic, thank you very much for your example.
    Help me please to improve my directive, this is created with your example. See please http://codepen.io/jdnichollsc/pen/mewBmj?editors=001
    I don’t want to change the scope, use ionGrid.$parent. is horrible :/

  • Luís Cunha

    Thanks a lot for this tutorial, was very helpful.

  • Frate Aubets

    It makes long since you post this great tuto. I’m a newbie in the Apps developing but I’m already on this world and next week I’ll start to develop the gallery of the app in which I’m working right now.
    Based on the ionic guys suggestion, I think that when we a iterating with media the use of http://ionicframework.com/docs/api/directive/collectionRepeat/ could be better.

    Nice work Nic!

  • ZiLang

    I’m wondering if it’s possible to add a separator between rows?

  • Thanks for the tutorial! I did get the error “Duplicates in a repeater are not allowed” but was able to fix that using the following solution: http://stackoverflow.com/a/17246507/1783311

  • Enamul Haque

    Hello Nic Raboy
    You have solved many problems. Please suggest me about the problem
    I have used

    Here On checked check box show images here

    It is accordion with check box .

    When check box is checked it is created . It is working nice

    But When i uncheck check box in the middle or any check box It remains blank in position. like that

    In controller I have used

    $scope.burgerItems = [

    ]

    $scope.toggleGroup = function(group) {
    if ($scope.isGroupShown(group)) {
    $scope.shownGroup = null;
    } else {
    $scope.shownGroup = group;
    }
    };
    $scope.isGroupShown = function(group) {
    return $scope.shownGroup === group;
    };

    $scope.radioValue=function(item){

    }

    Please help me to merge image if i uncheck check box it will not remain blank. help me to edit css sothat it won’t remain blank.
    Same thing i have done from database…

  • mt_nasty

    This a great read for Ionic, but teaches some solid ng-repeat fundamentals, as well! Thanks for sharing, @nicraboy:disqus

  • Periyasamy M

    Thanks for the tutorial …..very helpful and easy steps.
    I am a beginner of Ionic

    • No problem. I’m glad you found it useful!

  • THANK YOU for making this tut!!! It was exactly what I needed to overcome the issues I was facing. My grid works perfectly, and looks great: http://screencast.com/t/CvIlUeAS7j

    Thanks again, I love your blog and videos! I have learned so much!

  • madson g.

    I am trying to load the images from a json file return but it is not working. If I load them with your first html code it works fine. But when I change it to the second nothing is displayed. Can you help me? Here is my $scope holding the images array

    $scope.images = $state.params.dataToFotos.album;

    and the index in json file is {“FILE”:”path to image”}

    • What do your logs say?

      • madson g.

        I solved it. I had to change ng-src=”{{images[$index + 3].src}}” to ng-src=”{{images[$index + 3].FILE}}”. Thanks anyway! Do you have a tutorial to open that images in a full screen gallery?

  • Subhash viswakarma

    how to make zoom in this gallery

  • rahi

    Wow man what a great solution ! Really helped me big time !