Dynamic List Items in an Ionic/AngularJS App

In an Ionic/AngularJS app when one wants to display a list of model objects, the following will typically be used:

<ion-list>
  <ion-item ng-repeat="item in items">
    Hello, {{item}}!
  </ion-item>
</ion-list>

In an app I’m currently working on, however, I wanted to make use of different items in a list dynamically, with the appearance of each item depending on various properties of the given model object in the list. I’d imagine that to solve this problem there are various ways of doing so, but I ended up using html view templates and the ng-include directive to achieve this. Below is a step-by-step walkthrough of the method I used:

  • Define HTML view templates for the different list items to be displayed.

TemplateA.html

{{modelObject.name}}

TemplateB.html

<img class="full-image" ng-src="{{modelObject.image.url}}">
<p>
	{{modelObject.description}}
</p>
  • Add functions in the controller to determine the correct class & view template to use based on properties of the provided model object.

HomeCtrl.js

.controller('HomeCtrl', function($scope) {
  var vm = $scope;

  // Determines the correct CSS class to use based
  // on properties of the provided model object
  vm.itemClass = function(modelObject) {
    if (modelObject.type == 0) {
      return "class-A";
    }
    else {
      return "class-B"
    }
  };

  // Determines the correct html view template to use based
  // on properties of the provided model object
  vm.itemTemplate = function(modelObject) {
    if (modelObject.type == 0) {
      return "app/path_to_template/templateA.html";
    }
    else {
      return "app/path_to_template/templateB.html";
    }
  };
});
  • Then in the view displaying the list, it’s as simple as referencing the relevant controller functions to dynamically determine the correct class and template to use for each item in the list at runtime.

Home.html

    <ion-list>
      <ion-item ng-repeat="modelObject in modelObjects" ng-class="itemClass(modelObject)">
        <ng-include src="itemTemplate(modelObject)"></ng-include>
      </ion-item>
    </ion-list>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s