how to access forEach in angularjs

时间:2016-10-19 13:41:56

标签: javascript angularjs foreach

Brand new here sorry if I do something wrong. Here is my js fiddle https://jsfiddle.net/phorton/2rdyj9oe/2/

I am trying to convert this to angular. I am stuck on trying to capture each numCoins value.

this.calcAmount = function(amount) {
    amount = amount * 100
    var coins = [
        {name: 'quarters', value: 25}, 
        {name: 'dimes', value: 10},
        {name: 'nickles', value: 5}, 
        {name: 'pennies', value: 1}]

    coins.forEach(function (coin) {
      var numCoins = Math.floor(amount / coin.value)
      this[coin.name] = numCoins
      amount -= (numCoins * coin.value)
})

} The top part of my js fiddle works putting the values out in console.log. I need to store each iteration of numCoins and have it update each value on angluarjs. I am really lost sorry.

1 个答案:

答案 0 :(得分:0)

我建议在coins函数之外初始化calcAmount数组。您还可以在amount对象中添加coin字段,并在迭代数组时存储您在那里计算的数量。您可以使用它来显示结果。

这是一个更新的小提琴:https://jsfiddle.net/cpgoette/q51o7rsm/