【问题标题】:Angular: How to update DB with changes from input fields inside ng-repeatAngular:如何使用 ng-repeat 中输入字段的更改来更新数据库
【发布时间】:2020-07-15 22:36:57
【问题描述】:

我正在为个人项目(锦标赛)制作一个小的 Angular 页面。我使用存储所有匹配项的 Oracle 数据库。使用 PHP,我可以向该数据库发出请求并接收我存储在数组中的所有匹配项(来自团队的名称和目标)。

我使用 Angular (ng-repeat) 在我的页面上显示这个数组。如您所见,每行内都有输入字段,用于填写每支球队的进球数。现在,当您单击底部的按钮(见图)时,我想更新数据库中的所有行(通过 PHP)。

最简单的方法是什么?如何使用输入字段中的新值更改该数组并将它们发送到 DB?

HTML 代码:

<table>
<tr ng-repeat="wedstrijd in ophalen track by $index">
  <td class="ploeg">{{wedstrijd.ploeg1_naam}}</td>
  <td class="doelpunten"><input type="text" value={{wedstrijd.ploeg1_doelpunten}}></td>
  <td class="streepje">-</td>
  <td class="doelpunten"><input type="text" value={{wedstrijd.ploeg2_doelpunten}}></td>
  <td class="ploeg">{{wedstrijd.ploeg2_naam}}</td>
</tr>
</table>

我的页面截图:

【问题讨论】:

    标签: php angular oracle angularjs-ng-repeat


    【解决方案1】:

    可能有多种方式,按实例

    解决方案 1

    • 通过接口获取所有更新值的数组
    • 全部发送到后端

    解决方案 2

    • 通过接口获取所有更新值的数组
    • 一一发送到后端

    第一步很常见


    第 1 步 在 Angular 模板中,将 value="..." 更改为 [(ngModel)]="..." 双数据绑定将直接更新您的数组(ophalen)

    ...
    <td class="doelpunten"><input type="text" [(ngModel)]="wedstrijd.ploeg1_doelpunten"></td>
    ...
    

    第 2 步 在 Angular 控制器中,将您的数组发送到您的数组(ophalen)的 http 数据中

    constructor(...
                private updateService: UpdateService
                ...
    }
    
    // Called on button 'Updaten'
    onSubmit() {
        ...
        // Save
        this.updateService.save(this.ophalen).subscribe(
            (result: any) => {
                // Do something like echo message
            }
        );
    }
    

    第 3 步 创建一个 Angular 服务来调用您的后端 (PHP)。在这里,您可以选择一个一个或一次全部。无论如何,服务都会将您的数组作为输入参数。

    import {HttpClient} from '@angular/common/http';
    
    export class UpdateService {
        constructor(private http: HttpClient) {}
    
        saveAll(arrayModel: any): Observable<any> {
           const url = 'url/to/your/php/post/service';
           return this.http.post<any[]>(url, arrayModel);
           // Or loop on each and call saveOne...
        }
    
        saveOne(model: any): Observable<any> {
           const url = 'url/to/your/php/post/service';
           // with full model
           return this.http.post<any[]>(url, model);
           // or only with ids and new value
           return this.http.post<any[]>(url, {id:model.id, newValue:model.ploeg1_doelpunten);
        }
    
    }
    

    第 4 步 在 PHP 中,您必须创建一个/多个休息入口点。

    • 在 PHP 中解析 JSON 并在其上循环应该不会成为生成所需 SQL 更新语句的问题。
    • 如果你一个一个去,它是相同的SQL生成。只有你不需要明显循环。



    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      相关资源
      最近更新 更多