【问题标题】:Select multiple items, not just one (angularJs)选择多个项目,而不仅仅是一个(angularJs)
【发布时间】:2016-02-23 16:22:36
【问题描述】:

我已经在 div 中展示了产品,用户可以点击它们来选择它们。我的问题是只能选择一种产品。我不想将此功能更改为多选,并且功能应收集产品的 id。

这是我的产品 HTML

<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>

这是我用于选择项目的控制器功能

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

一旦项目被选中,div的背景是蓝色的

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

那么如何正确编写控制器函数,以便您可以选择多个 div 和$scope.selectd 变量收集产品的 id。

【问题讨论】:

  • 那么你有什么尝试?如果您将代码提供给我们,我们实际上可以提供帮助。
  • 也许你可以给我们一个最小的 JSFiddle 例子?
  • 到目前为止,我已经尝试将变量推送到数组中,但问题是取消选择项目。一旦我解决了这个问题,将 div 着色为蓝色就不起作用了,所以这就是为什么我将代码恢复到可以选择的时候
  • @Derlin 我正在研究它

标签: javascript angularjs


【解决方案1】:

目前,$scope.selected = index; 仅包含一个索引,您要么需要将其设为数组并切换当前选择:

变体 1

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

并更改您的 ngClass 定义:

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

变体 2

或更改您的ngClick-function:

 ng-click="selectUserItems(p)"

还有selectUserItems 函数

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

并更改您的 ngClass 定义:

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

【讨论】:

  • 哇,干得好。我什至没有时间去创造 pluker 或 fiddle。谢谢
【解决方案2】:

在产品对象中,添加一个字段'selected'来控制是否选中该项目。并在 ng-click 中切换selected 的值:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-04
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多