【问题标题】:How to add the values in angular js ng-repeat iteration within html layer?如何在 html 层中添加角度 js ng-repeat 迭代中的值?
【发布时间】:2017-11-22 04:18:49
【问题描述】:

请在下面找到我的代码

<ul id="cart-sidebar" class="mini-products-list" ng-init="cartArray.total = {}">
    <li class="item odd" ng-if="cartArray.length === 0">No items in your cart..</li>
    <li class="item odd" ng-repeat='y in cartArray'>
        <a href="shopping_cart.html" class="product-image"><img ng-src="" alt="" width="65"></a>
        <div class="product-details">
            <a href="#" title="Remove This Item" class="remove-cart" ng-click="removeFromCart(y)"><i class="pe-7s-trash"></i></a>
            <p class="product-name"><a href="shopping_cart.html">{{y.prodName}}</a> </p>
            <strong>1</strong> x <span class="price" ng-init='cartArray.total.prodAmt = cartArray.total.prodAmt + y.prodAmt'>Rs. {{y.prodAmt}}</span>
        </div>
    </li>
</ul>
<div ng-if="cartArray.length > 0" class="top-subtotal">Subtotal: <span class="price">{{cartArray.total.prodAmt }}</span></div>

例如,如果数组有 2 个值 100 和 200,则 {{cartArray.total.prodAmt }} 的预期输出为 300(sum),但我得到 100200(Concatenated string) 作为输出。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: angularjs angularjs-ng-repeat


    【解决方案1】:

    在进行加法运算前,请确保两个变量都是numeric类型(不是string),否则会给出拼接结果。

    stringnumeric 的转换可以使用许多选项,例如:

    1. 在变量前使用+。例如:+cartArray.total.prodAmt
    2. 使用函数Number()。例如:Number(cartArray.total.prodAmt)
    3. 使用parse 函数,如Math.parseIntMath.parseFloat 等,例如:Math.parseInt(cartArray.total.prodAmt)
    4. 乘以 1。例如:cartArray.total.prodAmt * 1

    所以改行ng-init='cartArray.total.prodAmt = cartArray.total.prodAmt + y.prodAmt'

    ng-init='cartArray.total.prodAmt = (+cartArray.total.prodAmt) + (+y.prodAmt)'

    ng-init='cartArray.total.prodAmt = Number(cartArray.total.prodAmt) + Number(y.prodAmt)'

    使用上述任何一种方法。

    【讨论】:

    • 这些都有效,但也可能值得将控制器本身的逻辑也移动到内部。文档建议不要滥用 ng-init:docs.angularjs.org/api/ng/directive/ngInit
    • @Cracker 使用上面的代码,当我更改数量文本框中的值时,
    猜你喜欢
    • 1970-01-01
    • 2016-04-23
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 2017-07-24
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多