Ionic ListView 101

Most mobile apps at some point need to show a list of data in a tableview of some kind. Let’s take a quick look at how you might do this. For our example, we’re going to look at a simple list of products that you might have in an app.

As is pretty common with Ionic, it all starts in the controller and with the $scope variable:

$scope.$on('$ionicView.enter', function (viewInfo, state){
$scope.data.products = Products.getProducts();
})

Here we are assuming that you have a Products factory or service with a getProducts() method that returns an array of products. Note that we are setting products to $scope.data rather than just $scope this is considered a best practice in Ionic but is not altogether required.

Now let’s take a look and breakdown the template for the view to see how this all comes together:

<ion-list>
<ion-item class="item-avatar item-icon-right" ng-repeat="product in data.products" type="item-text-wrap">
<h2>{{product.name}}</h2>
<p>{{product.price}}</p>
<i class="icon ion-chevron-right icon-accessory"></i>
</ion-item>
</ion-list>

We’re using the ion-list class here rather than just ul but we should note that you can actually do something similar with a plain ul and li combination which would look something like:

<ul>
<li class="item-avatar item-icon-right" ng-repeat="product in data.products" type="item-text-wrap">
<h2>{{product.name}}</h2>
<p>{{product.price}}</p>
<i class="icon ion-chevron-right icon-accessory"></i>
</li>
</ul>

One disadvantage to not using the Ionic provided version in general is that you wouldn’t get all of the Ionic styling “for free” but most of that can be made up for by applying their CSS styles as done here. We’re not going to get into whether you generally should use the Ionic versions over the plain HTML ones but it’s important to know that there are options and advantages to both approaches. In both examples above, all of the work is done by item itself via ng-repeat="product in data.products. That’s a directive from the AngularJS side of Ionic that iterates through a collection of items and repeats the UI element for each item in the collection. So in our case, it runs through all the products in the array and makes a row for all of them.

That’s it! There’s of course a lot going on under the covers in Angular / Ionic but for the purpose of a quick “how to” that’s as far as we’re going to go into in this post. Please follow us on Twitter and if you have a mobile or web project you’re looking to get off the ground, please get in touch by filling out the contact form on this page.