我正在尝试构建一个媒体库,其中一次只能选择一个图像。为此,我有一个使用AngularJS的ng-repeat函数生成的列表。到目前为止,当我单击一个元素时,它会向子div添加一个突出显示类,并切换子表单元素的可见性。如何使点击与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>
答案 0 :(得分:3)
您可以将显示的媒体保存在控制器的临时变量中,并具有2个功能1)点击项目2)设置媒体对象可以显示检查对象相等的功能。
控制器:
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
}
查看:
<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>
示例实施演示
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>
答案 1 :(得分:1)
这应该有效
<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>