【问题标题】:Angularjs - ng-repeat and nested scopeAngularjs - ng-repeat 和嵌套范围
【发布时间】:2018-07-17 06:48:52
【问题描述】:

我是 angularjs 的新手,并试图掌握在嵌套范围内访问数据的概念。 这是包含对象“联系人”的嵌套范围的主要范围“公司”:

$scope.company = 
      {
        companyName: "",
        contacts: {
          name: "",
          email: ""
        }
      }

我正在尝试生成一个表格,其中包含每一行中“联系人”范围内的数据。

 <tr ng-repeat="contact in company.contacts">
                    <td>
                        <input type="text" class="form-control" ng-model="contact.name"/>
                    </td>
                    <td>
                        <input type="text" class="form-control" ng-model="contact.email"/>
                    </td>
                </tr>

但似乎我在这里做错了,因为当我尝试显示主范围 {{company}} 中的数据时,实际上并没有发生任何事情。

我真的可以使用一些建议。谢谢。

【问题讨论】:

  • 在您的示例中,联系人是一个对象,而不是一个数组。循环用于遍历数组/列表
  • 感谢您指出这一点。如何使用 ng-repeat 访问对象?
  • 查看答案,我无法在保留良好格式的同时将其变成评论

标签: angularjs-ng-repeat


【解决方案1】:

您不想为此使用循环。 只需使用company.contacts.namecompany.contacts.email

但是我怀疑您可能想要多个联系人,因此需要多个联系人。为此,您需要将联系人设为数组。 使用数组,您可以使用重复。

像这样:

$scope.company = 
      {
        companyName: "",
        contacts: [
         {
          name: "",
          email: ""
         },
         {
          name: "",
          email: ""
         }
        ]
      }

题外话:如果您刚刚学习 Angular1,并且还没有正在处理的大型项目,请切换到 Angular2+(目前为 6 个)。 AngularJs (1.x) 是一个仅长期支持一年半的框架。 (AngularJs (1.x) 和 Angular (>= 2 ) 是不同的框架。)

【讨论】:

  • 非常感谢您的澄清。将联系人设置为数组非常有效!我可以再问一个问题以确保我走在正确的轨道上吗?访问数组联系人中的最后一项是否正确: var last = $scope.company[$scope.company.contacts.length - 1];至于 offtop - 这是我实习任务的一部分,所以我别无选择,只能使用 angularjs :) 所以谢谢你帮助我。
  • length - 1 很好,你也可以使用$scope.company.contacts.last()。没问题,别忘了将其标记为已解决;)(已接受答案或其他内容)
  • 再次感谢您,您的评论非常有帮助。我会看看如何将问题标记为已解决:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 2018-12-23
  • 1970-01-01
相关资源
最近更新 更多