Ionic framework: Different background color for ea

2019-05-07 00:53发布

I would like to have a different background color for every list-item using ionic. For example a list of fruit containing: banana, apple, orange... For banana the background would be yellow For apple, it would be green For orange, it would be yellow ...

Does anyone have an idea on how to achieve this?

I have tried to work with ng-style and ng-class but I did not succeed to obtain the wanted result.

I use collection-repeat for the list.

Thank you!

EDIT:

http://plnkr.co/edit/L80IcehgBQTiVXCCLWo9?p=preview

HTML

<!DOCTYPE html>
<html ng-app="myApp">
<head>

  <script src="http://code.ionicframework.com/nightly/js/ionic.bundle.js?4"></script>
  <script src="script.js"></script>
  <link rel="stylesheet" href="http://code.ionicframework.com/nightly/css/ionic.css">
</head>
<body ng-controller="MainCtrl as main">
  <ion-header-bar class="bar-positive">
    <h1 class="title">1000 Items</h1>
  </ion-header-bar>
  <ion-content>
    <ion-list>
      <ion-item collection-repeat="item in main.items" ng-class="item == '0' ? 'classA' ">
        {{item}}
      </ion-item>
    </ion-list>
  </ion-content>
</body>
</html>

JS

var myApp = angular.module('myApp', ['ionic']);

myApp.controller('MainCtrl', function() {
  this.items = [];
  for (var i = 0; i < 1000; i++) this.items.push(i);
});

CSS

.classA { 
    background-color: black;


}

3条回答
乱世女痞
2楼-- · 2019-05-07 01:24

Your ng-class expression in error.

It should be ng-class="item == '0' ? 'classA' : ''"

Plus, you haven't included your style.css in index.html:

<link rel="stylesheet" href="style.css">

This is the plunker.

查看更多
SAY GOODBYE
3楼-- · 2019-05-07 01:25

Easiest way to achieve alternating row or list item background color is to use AngularJS directive ng-class-even and ng-class-odd.

https://docs.angularjs.org/api/ng/directive/ngClassEven

查看更多
该账号已被封号
4楼-- · 2019-05-07 01:35

Try following code:

CSS

ion-item[isOdd='true'] > div.item-content{
    background-color: yellow !important;
}

ion-item[isOdd='false'] > div.item-content{
    background-color: orange !important;
}

HTML

<ion-item collection-repeat="item in main.items" isOdd="{{$odd}}">
查看更多
登录 后发表回答