Apply logic to every element in an ng-repeat upon ng-click (AngularJS)

半腔热情 提交于 2020-01-03 05:00:07

问题


I'm trying to build a media library in which only one image can be selected at a time. To do this, I have a list generated with AngularJS's ng-repeat function. So far, when I click on an element, it adds a highlighting class to a child div and toggles the visibility of a child form element. How can I make the click do the opposite for every other element in the ng-repeat?

<li ng-click="show=!show" ng-repeat="media in media">
    <div ng-if="show" class="selected">
        <input class="bulk-check" type="hidden" name="ids[]" value="@include('_helpers.media_id')">
    </div>
</li>

回答1:


You could just save displayed media in a temp variable in your controller and have 2 functions 1) set the media object on click of item 2) can show function which checks for object equality.

Controller:

  var shownMedia = $scope.medias[0]; //Set you default media

  $scope.selectMedia = function(media) {
    shownMedia = media; //on click, set the new media as selected media
  }

  $scope.canShow = function(media) {
    return angular.equals(shownMedia, media); //Check if this is the displayed media
  }

View:

   <li ng-click="selectMedia(media)" ng-repeat="media in medias">
      {{media.name}}
      <div ng-if="canShow(media)" ng-class="{selected : canShow(media)}">
        {{media.description}}
        <input class="bulk-check" type="hidden" name="ids[]" value="@include('_helpers.media_id')">
      </div>
    </li>

Example implementation Demo

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.medias = [{
    name: 'media1',
    description: "media1"
  }, {
    name: 'media2',
    description: "media2"
  }, {
    name: 'media3',
    description: "media3"
  }];

  var shownMedia = $scope.medias[0];

  $scope.selectMedia = function(media) {
    shownMedia = media;
  }

  $scope.canShow = function(media) {
    return angular.equals(shownMedia, media);
  }

});
.selected{
  color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <ul>
    <li ng-click="selectMedia(media)" ng-repeat="media in medias">
      <span ng-class="{selected : canShow(media)}">{{media.name}}</span>
      <div ng-if="canShow(media)">
        {{media.description}}
        <input class="bulk-check" type="hidden" name="ids[]" value="@include('_helpers.media_id')">
      </div>
    </li>
  </ul>
</div>



回答2:


This should work

<li ng-repeat="media in mediaList"  ng-click="media.show=!media.show" >
    <div ng-if="media.show" class="selected">
        <input class="bulk-check" type="hidden" name="ids[]" value="@include('_helpers.media_id')">
    </div>
</li>


来源:https://stackoverflow.com/questions/27696932/apply-logic-to-every-element-in-an-ng-repeat-upon-ng-click-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!