如何在JavaScript对象中输出元素?

时间:2015-12-28 10:45:05

标签: javascript angularjs

范围内定义的对象:

$scope.products = [
    {
      name: 'custom',
      category: {
        name:'custom', 
        templateAttribute: [
          {attribute: 'material'},
          {attribute: 'soles'},
          {attribute: 'size'}
        ]
      }
    }
  ];

HTML:

<table class="table" ng-repeat="attr in products.category.templateAttribute">
            <tbody>
        <tr>
            <td>
                <input value="{{attr.attribute}}" />
            </td>
            <td>
                <input placeholder="name" ng-model="product.attributes[attr.attribute].name" />
            </td>
            <td rowspan="2">
                <button type="button" ng-click="addItem(product.category.templateAttribute, attr)">
                add
              </button>
            </td>
        </tr>
            </tbody>
        </table>

我希望输出看起来每个属性都有输入形式

它看起来应该如何运作:

<table class="table" ng-repeat="attr in products.category.templateAttribute">

如何修复它?

2 个答案:

答案 0 :(得分:2)

由于$ scope.product是一个数组 $ scope.product.category本身未定义

必须像

<table class="table" ng-repeat="attr in products[0].category.templateAttribute">

如果产品是动态的

<table class="table" ng-repeat="product in products">
    <tr>
         <td ng-repeat="attribute in product.category.templateAttribute">
            <td><input value="{{attr.attribute}}" /></td>
            <td>
                <input placeholder="name" ng-model="product.attributes[attr.attribute].name" />
            </td>
            <td rowspan="2">
                <button type="button" ng-click="addItem(product.category.templateAttribute, attr)">
                add
              </button>
            </td>
         </td>
    </tr>

</table>

因此表将根据$ scope.products数组中的对象重复

答案 1 :(得分:0)

如果提供的HTML代码是您的整个模板,则假设存在错误 ng-repeat =“attr in products.category.templateAttribute”迭代products [0] .category对象中的“templateAttribute”数组。

您实际上需要两个ng-repeats,一个用于迭代产品数组,另一个用于迭代每个产品中的category.templateAttribute:

<table class="table" ng-repeat="product in products">
    <tr>
         <td ng-repeat="attr in product.category.templateAttribute">
                <input value="{{attr.attribute}}" />
                .....
         </td>
    </tr>

</table>