2016-02-23 42 views
1

我已经在div中显示产品,用户可以点击它们来选择它们。我遇到的问题是只能选择一种产品。我不想将此功能更改为多选,功能应该收集产品的ID。选择多个项目,而不只是一个(angularJs)

这是我的产品

<div class="product_item hit w_xs_full" ng-repeat="p in products track by $index" style="float: left; background-color: blue;"> 
    <figure class="r_corners photoframe type_2 t_align_c tr_all_hover shadow relative" 
      ng-click="selectUserItems($index)" ng-class="{sel: $index == selected}"> 
     <!--product preview--> 
     <img ng-src="images/products/{{p.images[0].thumbName}}" alt="{{p.name}}" class="tr_all_hover"> 
     <!--description and price of product--> 
     <figcaption> 
      <br> 
      <h5 class="m_bottom_10"><b>{{p.name}}</b></h5> 
      <p class="scheme_color f_size_large m_bottom_15" style="color:black;">Located in: <b>{{p.country}}</b></p> 
      <a href="#/swap/{{p.mainCategorieLink}}/{{p.subCategoryLink}}/{{p.alias}}"> 
       <button class="button_type_4 bg_scheme_color r_corners tr_all_hover color_light mw_0 m_bottom_15">See item</button> 
      </a> 
     </figcaption> 
    </figure> 
</div> 

HTML,一旦所选项目的div的背景为蓝色,这是我选择的项目

//select items 
$scope.selectUserItems = function(index){ 
    $scope.selected = index; 
}; 

控制器功能

.sel { 
    background-color:#5ACBFF; 
} 

所以如何正确编写控制器功能,以便您可以选择多个div和$scope.selectd变量收集产品的ID。

+0

那么你有什么尝试?如果你给我们你的代码,我们实际上可以提供帮助。 –

+0

也许你可以给我们一个最小的JSFiddle例子? – Derlin

+0

到目前为止,我试图推动数组中的变量,但问题是取消选项。一旦我解决了这个问题,着色div蓝色不起作用,所以这就是为什么我恢复代码,当我可以选择一个 –

回答

1

目前,$scope.selected = index;只保存一个索引,你要么需要使它的数组,并切换目前的选择:

变1

$scope.selected[index] = !$scope.selected[index]; 

,改变你的ngClass定义:

ng-class="{sel: $index[selected]}" 

变2

或更改ngClick功能全:

ng-click="selectUserItems(p)" 

而且selectUserItems功能

$scope.selectUserItems = function(item){ 
    item.selected = !item.selected; 
}; 

,改变你的ngClass定义:

ng-class="{sel: p.selected}" 
+0

哇,很好的工作。我甚至没有时间去创造一些短裤或小提琴。 Thx –

+0

很高兴工作,欢呼:) –

1

在产品对象中,添加一个字段'selected'来控制是否选择该项目。并切换在selected值NG点击:

<figure class="...." ng-init="p.isSelected = false" 
     ng-click="p.isSelected = !p.isSelected" ng-class="{sel: p.isSelected}"> 
相关问题