【问题标题】:AngularJS ng-repeat print 0 if any object missed如果任何对象丢失,AngularJS ng-repeat 打印 0
【发布时间】:2017-04-14 11:25:47
【问题描述】:

第二个数组中缺少一个对象。在那里使用 ng-repeat 我想打印 0。请找到以下代码

<div ng-repeat="item in items">
      {{item}}
      <div>
        <h3>{{item[0].name}}</h3>
        <div>
          <article>
            {{item[0].tc}}
          </article>
          <article>
            {{item[1].tc}}
          </article>
          <article>
            {{item[2].tc}}
          </article>
        </div>
      </div>
    </div>

code in plunker

【问题讨论】:

  • 你可以使用这样的东西{{item[2] ? item[2].tc : "0"}}
  • 只需在表达式{{item[2].tc || 0}}中添加一个OR
  • 谢谢...为我工作

标签: javascript html angularjs arraylist


【解决方案1】:

打印对象或零

  <article>
    {{item[2].tc || 0}}
  </article>

或者

  <article>
    {{item[2].tc ? item[2].tc : 0}}
  </article>

【讨论】:

    【解决方案2】:

    查看 plunkr 中的数组 - 似乎您必须对 items 数组进行两次迭代:

    //array from the plunkr
        $scope.items = [
          [{name:"a",tc:100}, {name:"a",tc:101}, {name:"a",tc:102}],
          [{name:"d",tc:103}, {name:"d",tc:104}],
          [{name:"f",tc:105}, {name:"f",tc:106}, {name:"f",tc:107}]
        ]
    

    嵌套的 ng-repeats - 每个 items.array 一个,然后是该数组中的每个对象。假设每个对象都具有相同的名称 - 可以为 h3 获取第一个对象 - 但是使用嵌套的 ng-repeat 将允许检索数组中的对象 - 无论它们的数量如何。

    <div ng-repeat="item in items">
        {{item}}
          <div>
            <h3>{{item[0].name}}</h3>
            <article ng-repeat="itemDetail in item">
              {{itemDetail.tc}}
            </article>
          </div>
        </div>
    

    【讨论】:

      【解决方案3】:

      例如,如果item[0] 丢失,则item[0].name 将导致错误Can not read property name of undefined。您需要为您的数据设置默认值或使用{{(item[0] || {}).name}}

      【讨论】:

      • "将导致错误" ...不在视图表达式中它不会。您是否在演示中的控制台中看到此类错误?空对象也不会产生预期的结果
      【解决方案4】:
      <body ng-controller="MainCtrl">
          <div ng-repeat="item in items">
            {{item}}
            <div>
              <h3>{{item[0].name}}</h3>
              <div>
                <article>
                  {{item[0].tc}}
                </article>
                <article>
                  {{item[1].tc}}
                </article>
                <article>
                  <span ng-hide="item[2].tc">0</span>
                  {{item[2].tc}}
                </article>
              </div>
            </div>
          </div>
        </body>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多