在AngularJS中动态更新数据

时间:2018-07-22 23:55:37

标签: javascript angularjs

我有两个终点

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

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

http://localhost:3000/entries(获取)

它将以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>

script.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;
                    };
            }
});

1 个答案:

答案 0 :(得分:0)

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

首先,您需要对控制器进行一些扩展。主要的是从您的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">元素来实现。