【问题标题】:How should I apply a conditional class for nested objects in angularjs我应该如何为 angularjs 中的嵌套对象应用条件类
【发布时间】:2013-08-02 02:19:30
【问题描述】:

我实际上是在尝试显示/隐藏部分的标题,基于点击事件,该事件也用于过滤标题下方的ng-repeat

我的想法是通过重用我用于过滤功能的ng-click 来切换一个类。我的过滤器在 ng-repeat 上运行良好,但我似乎无法让条件类在标题上运行。

下面是(简化的)代码:

<div ng-init="phones = [
            {name:'Samsung Galaxy S II', product_type: 'android'},
            {name:'iPhone 5', product_type: 'ios'},
            {name:'Samsung Galaxy S II', product_type: 'android'},
            {name:'iPhone 5', product_type: 'ios'},
            {name:'Samsung Galaxy S II', product_type: 'android'},
            {name:'iPhone 5', product_type: 'ios'}
        ]">

    <!-- Filters for products -->

    <a href="#" ng-click="property = null">All</a>
    <a href="#" ng-click="property = {product_type:'android'}">Android</a>
    <a href="#" ng-click="property = {product_type:'ios'}">iOS</a>

    <!-- Android Product Section -->

    <h2 ng-class="{true: 'hide', false: 'show'}[property == {product_type:'ios'}]">Android</h2>

    <div ng-repeat="phone in phones | filter:property | filter:{product_type:'android'}">
        <h3>{{ phone.name }}</h3>
    </div>

    <!-- iOS Product Section -->

    <h2 ng-class="{true: 'hide', false: 'show'}[property == {product_type:'android'}]">iOS</h2>  

    <div ng-repeat="phone in phones | filter:property | filter:{product_type:'ios'}">
        <h3>{{ phone.name }}</h3>
    </div>
</div>

这是我的代码演示:http://codepen.io/micjamking/pen/c0cfb8039492204d0282c42f563983e0

仅供参考,我无法更改上述 JSON(对象数组)的结构/方案。我实际上是从服务中的 API 获取数据,但认为这将是一种显示视图中正在发生的一切的简单方法。

我真诚地感谢任何人对此提供的帮助或建议。

【问题讨论】:

  • 你能不能把表达式property == {product_type:'android'}改成"property.product_type==='android'"

标签: css arrays class object angularjs


【解决方案1】:

看起来您的 ng-class 指令比它需要的要复杂一些。我将其更新为如下所示:

<h2 ng-class="{invisible: property.product_type =='ios'}">Android</h2>
...
<h2 ng-class="{invisible: property.product_type =='android'}">iOS</h2>  

这里有一个 jsFiddle 来演示:http://jsfiddle.net/jandersen/ZFDQT/1/

invisible 类取自您的 codepen 示例)

【讨论】:

  • 完美!谢谢@jandersen。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
相关资源
最近更新 更多