Search code examples
angularjsfilterangularjs-ng-repeat

How do I create a filter for the <img> tag?


I try to filter to show img depend on dropdown id, but it isn't work as desired. Where did i go wrong? Both filter isn't worked. Here what i try so far

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
  <div ng-app="myApp" ng-controller="namesCtrl">
    <select class="form-control">
      <option ng-repeat="data in day_month_select_menu" ng-model="data.id"
      value="{{data.id}}">{{data.selectText}}</option>
    </select>
    <img ng-repeat="data in day_month_select_menu |filter : data.id" src="{{data.img}}" 
    alt="Error" />
    <ul>
      <li ng-repeat="data in day_month_select_menu | filter:data.id">
        {{ data.show }}
      </li>
    </ul>
  </div>

  <script>
    angular.module('myApp', []).controller('namesCtrl', function($scope) {
      $scope.day_month_select_menu = [
      {
        id : 1, selectText:"day", show:"Monday", img:"tmp"
      },
      {
        id : 2, selectText:"date", show:"Dec 12th 2018", img:"tmp2"
      }
      ];
    });
  </script>
</body>

Solution

  • Does this work as you intended?

       angular.module('myApp', []).controller('namesCtrl', function($scope) {
          $scope.day_month_select_menu = [
          {
            id : 1, selectText:"day", show:"Monday", img:"tmp"
          },
          {
            id : 2, selectText:"date", show:"Dec 12th 2018", img:"tmp2"
          },
          {
            id : 3, selectText:"Test", show:"Dec 13th 2018", img:"tmp3"
          }
          ];
        });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
      <div ng-app="myApp" ng-controller="namesCtrl" >
        <select class="form-control" ng-model="selectedMenuOption" >
          <option ng-repeat="menuOption in day_month_select_menu" 
          value="{{menuOption.id}}" >{{menuOption.id}} - {{menuOption.selectText}}</option>
        </select>
        <!--
        <br/>selected:{{selectedMenuOption}}
        <hr/>
        -->
        <ng-container ng-repeat="data in day_month_select_menu"  >
          <span ng-if="data.id == selectedMenuOption">
          <br/>{{data.id}} & {{selectedMenuOption}}: <img src="{{data.img}}" alt="Error" /> 
          <span>
        </ng-container>
        
        <ul>
          <li ng-repeat="data in day_month_select_menu | filter:data.id">
            {{ data.show }}
          </li>
        </ul>
      </div>