【问题标题】:OneToMany mapping on AngularJS pageAngularJS 页面上的 OneToMany 映射
【发布时间】:2019-10-02 21:33:00
【问题描述】:

我们如何在具有 Onetomany 映射的 AngularJS 页面上编写输入字段?

User Class has Name and phone attributes and can have multiple phone numbers.

AngularJS code for fName input field

<input tabindex="10" style="width: 60%;" type="text" ng-model="ctrl.user.fName" placeholder="First Name">

''''用于电话映射的 AngularJS 代码 - 因为这是一个 OneToMany 字段,所以我在 User 类中使用了 List,现在我在 AngularJS 页面上有 3 个输入文本字段 - 那么我如何编写 ng-model 相同的,对于第一个文本字段,我已经声明如下,但是第二个和第三个文本字段呢?如何为电话字段声明 ng-model。

<input type="text" ng-model="ctrl.user.phone.phoneNumber" placeholder="Parking #">

【问题讨论】:

    标签: angularjs spring-boot


    【解决方案1】:

    基本答案是使用*ngFor,但我不确定这是否是您用例的最佳方法。

    <div *ngFor="number of ctrl.user.phone.phoneNumbers">
      <input type="text" ng-model="number" placeholder="enter a new number">
    </div>
    

    如果您只打算拥有三个号码,则为每个号码指定特定的电话类型可能会更容易:

    <input type="text" ng-model="ctrl.user.phone.homePhone" placeholder="Home #">
    <input type="text" ng-model="ctrl.user.phone.cellPhone" placeholder="Cell #">
    <input type="text" ng-model="ctrl.user.phone.workPhone" placeholder="Work #">
    
    

    最后,根据您使用的 Angular 版本,您可能会发现实现 FormControl 比使用 ng-model 更容易。

    【讨论】:

    • 谢谢@Ben Hulan,我会尝试使用上面的方法。
    • 如何使用这个
      。我的意思是这样屏幕上只有一个文本框,那么第二个和第三个输入框呢?
    • 当我说我不确定这是否是您的用例的最佳方法时,这就是我的意思。 *ngFor 只会在您的数据模型结构包含多个 phoneNumber 类型时呈现多个输入。我认为您想使用 FormControl 而不是 ng-model。如果您告诉我您使用的是哪个版本的 Angular,我可以为您指明正确的方向;不同版本的语法变化很大。
    • 我正在使用 AngularJS v1.5.8,感谢您的帮助。我将探索 formControl。
    • This post 可能对您有用。如果您的问题得到解答,请投票。
    【解决方案2】:

    所以我能够找到答案,令人惊讶的是,任何门户网站上都没有太多关于此问题的材料。

    所以问题是如何在 AngularJS 和任何后端(如 Springboot 和 Hibernate)中使用 OneToMany 映射。

    前用户有直接列,如姓名、年龄、出生日期等,但可以说用户与对象联系人(还有电话号码、电子邮件、紧急联系人等)有一个映射

    在 Agular 中,我们可以直接将 ng-bind 放在名称字段上,如 ctrl.use.name 但对于 phonenumber 字段,它是通过以下方式指定的

    ctrl.user.contact[0].phonenumber

    请注意,现在在用户类中,您必须创建一个接受这样的联系人数组的设置器-

    public void setContact(Contact[] contacts){....实现}

    所以现在在用户表单上我可以有多个联系人对象,这些对象将作为 OneToMany 关系持续存在。

    【讨论】:

      猜你喜欢
      • 2012-10-18
      • 1970-01-01
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多