首页 > 解决方案 > 在 AngularJS 中动态更新数据

问题描述

我有两个端点

http://localhost:3000/entry (POST)

键是:- fname、lname 和 age 。我们可以通过向该 URL 发送 POST 请求来提交表单。

http://localhost:3000/条目(​​获取)

它将以 JSON 格式返回数据库中的现有数据。

[
    {
        "_id": "5b48a137c3b2a3454b853a3c",
        "fname": "John",
        "lname": "Jose",
        "age": "28",
        "__v": 0
    },
    {
        "_id": "5b506cc7d9105012f59c87e6",
        "fname": "Alex",
        "lname": "Cruz",
        "age": "27",
        "__v": 0
    }
]

我可以成功提交表格。在我的 HTML 中,我还有一个表格。每当我提交条目而不重新加载整个页面时,我都想更新表中的数据。

实际上,这个 API http://localhost:3000/entries中的数据是动态的,有时我直接插入到数据库中。因此,无论何时发生变化,它都应该反映在表格中,而无需重新加载整个页面。

我正在使用 AngularJS 1。

index.html :-

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">


<div ng-app="myApp">
  <div class="container">

    <div class="row">
      <div class="col-sm-12">
        <h3>
          Dashboard
        </h3>
      </div>
    </div> 

    <form name="saveTemplateData" action="#" ng-controller="FormCtrl"  ng-submit="submitForm()" >
      <div class="col-sm-12">
        <div class="form-group">
          <label>FirstName</label>
          <input type="text" class="form-control" value="" ng-model="form.fname" />
        </div>
        <div class="form-group">
          <label>LastName</label>
          <input type="text" class="form-control" value="" ng-model="form.lname" />
        </div>
        <div class="form-group"> 
          <label>Age</label>
          <input type="text" class="form-control" value="" ng-model="form.age" />
        </div>
      </div>
      <div class="col-sm-12">
        <input type="submit" class="btn btn-success" ngClick="Submit">
      </div>
    </form> 


    <!-- Table Start -->

    <div class="row">
      <table style="width:100%">
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Age</th>
        </tr>
        <tr>
          <!-- item.fname -->
          <td>{{item.fname}}</td>
          <!-- item.lname -->
          <td>{{item.lname}}</td>
          <!-- item.age -->
          <td>{{item.age}}</td>
        </tr>
      </table>
    </div>
    <!-- Table END -->

  </div>
</div>

脚本.js:-

var app = angular.module('myApp', []);
app.controller('FormCtrl', function ($scope, $http) {
$scope.submitForm = function()
            {
                $http({
                        url: "http://localhost:3000/entry",
                        method: "POST",
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        data: $.param($scope.form)
                    }).then(function (response) {
                        $scope.status = status;
                    }), function (error) {
                        $scope.status = status;
                    };
            }
});

标签: javascriptangularjs

解决方案


如果我了解您的问题和问题,您需要做很多事情来解决您的问题。

首先,您需要对控制器进行一些扩展。主要是从您的 API 中获取数据:

app.controller('FormCtrl', function ($scope, $http, $interval) {

/*
Add this method to get data from server
*/
$scope.fetchData = function() {

    // It is best practice to handle error responses as well (not 
    // shown here)
    $http.get('http://localhost:3000/entries').then(function(response) {

        // Set the data items in your scope. Doing this should now 
        // cause them to be listed in your view
        $scope.items = response.data;
 });

}

$scope.submitForm = function($event) {

    // Adding this prevents the browser from reloading on form submit
    $event.preventDefault()

    $http({
            url: "http://localhost:3000/entry",
            method: "POST",
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            data: $.param($scope.form)
        }).then(function (response) {
            $scope.status = status;
        }), function (error) {
            $scope.status = status;
    });
}

// Fetch data once controller is set up, on a regular 2 second 
// interval
$interval(function() {
   $scope.fetchData()
}, 2000)
});

您还需要更新您的 HTML/视图:

<!-- Add $event as an argument to you ng-submit callback -->
ng-submit="submitForm($event)"

和:

<!-- Doing this causes the data in the items array to be iterated
     and displayed in a list-wise fashion in the table -->
<tr ng-repeat="item in items">
    <!-- item.fname -->
    <td>{{item.fname}}</td>
    <!-- item.lname -->
    <td>{{item.lname}}</td>
    <!-- item.age -->
    <td>{{item.age}}
    </td> 
</tr>

最后,最重要的是用FormCtrl控制器包装表格和表单。您可以通过ng-controller="FormCtrl"从您的<form>元素移动到<div class="container">视图中的元素来做到这一点。


推荐阅读