Angular动态访问对象属性

时间:2015-10-23 19:47:30

标签: javascript angularjs

我需要动态访问循环中的不同对象属性,但似乎无效。

<tr ng-repeat="item in Items">
    <td>
        {{item.itemName}} <!-- OK -->
    </td>
    <td ng-repeat="monthName in months.monthName">
        <input class="form-control text-right"
               value="{{item.monthName}}" <!-- KO -->
               <!-- value="{{item.january}}"  OK -->
               >
    </td>                             
</tr>

2 个答案:

答案 0 :(得分:2)

你需要使用bracket notation,即

  <input class="form-control text-right"
           value="{{item[monthName]}}"

我不确定您在此处使用value的意图是否正确,但如果您打算使用ng-model,那么它将是:

  <input class="form-control text-right"
           ng-model="item[monthName]"

否则,您指的是对象monthName的属性item,而不是名称代表对象monthName的{​​{1}}的值的属性。

答案 1 :(得分:1)

您正在尝试访问对象monthName中名为item的属性。 如果您想使用monthName作为标识符来检索item.january之类的内容,则可以使用符号item[monthName] 代码看起来像这样

<tr ng-repeat="item in Items">
    <td>
        {{item.itemName}} <!-- OK -->
    </td>
    <td ng-repeat="monthName in months.monthName">
        <input class="form-control text-right"
               value="{{item[monthName]}}" <!-- OK -->
               >
    </td>                             
</tr>
相关问题