Soul Eater
Soul Eater

Reputation: 505

Show an image (or icon) when a boolean value is TRUE with AngularJS?

So I have a list which have a column with boolean values in case some item have an attached file, when it does have an attachment it will show a "clip" icon. I want to do the same with an AngularJS table:

This is my code, HTML:
Notice there's a custom filter ("booleanFilter") in the {{link.Attachments}}

<body ng-app="myApp">
<div ng-controller="myController">
 <table>
  <thead>
   <tr>
    <th>Attachments</th>
    <th>Name</th>
    <th>Date</th>
   </tr>
  </thead>
  <tbody>
   <tr ng-repeat="link in links">
    <td>{{link.Attachments | booleanFilter}}</td>
    <td>{{link.Name}}</td>
    <td>{{link.Date | date:"MM/dd/yyyy"}}</td>
   </tr>
  </tbody>
 </table>
</div>
</body>

Here's my SCRIPT of my filter:
I want to show an Attachment Image when there is an attachment (when it's true) and show nothing when it's false:

var myApp = angular
            .module('myApp', [])
            .filter('booleanFilter', function() {
              return function(booleanFilter) {
                switch(booleanFilter) {
                  case true:
                       return "clip.png";
                  case false:
                       return "";
                }
              }
            })

The bad thing with this code is that it shows "clip.png" as a string instead of showing the icon picture, also I tried putting a Material Icon's code:

<i class="material-icons">attach_file</i>

But it won't work... so any ideas or is there something I've been doing wrong?

Upvotes: 3

Views: 6598

Answers (3)

Akshay Raut
Akshay Raut

Reputation: 413

If your flag is Attachments which can have true or false value then you don't even need filter:

  <tbody>
   <tr ng-repeat="link in links">
    <td><i ng-if="link.Attachments" class="material-icons">attach_file</i></td>
    <td>{{link.Name}}</td>
    <td>{{link.Date | date:"MM/dd/yyyy"}}</td>
   </tr>
  </tbody>

Upvotes: 1

AlexFF1
AlexFF1

Reputation: 1283

You could make is simpler using ng-if

 <tr ng-repeat="link in links">
<td>{{link.Attachments | booleanFilter}}</td>
<i  ng-if="(link.Attachments)>0" class="material-icons">attach_file</i>
<td>{{link.Name}}</td>
<td>{{link.Date | date:"MM/dd/yyyy"}}</td>

So if "link.Attachment > 0" or in your case can be == true/false then show the icon, applying css class "material-icons" or your custom class

Upvotes: 0

T.Liu
T.Liu

Reputation: 512

Try to load local image with:

app.controller('myCtrl', function($scope, $sce) {
  $scope.attachImg = $sce.trustAsResourceUrl('path/clip.png');
});

Then use ngSrc directive:

<img ng-src="{{attachImg}}">

Upvotes: 0

Related Questions