【问题标题】:Refresh table after $http post using angularjs, php and mysql使用 angularjs、php 和 mysql 在 $http 发布后刷新表
【发布时间】:2016-01-26 16:34:39
【问题描述】:

$http 方法发送数据后,我需要刷新表格以显示新添加的行。下面是我将表单值添加到 mysql 表的工作代码。感谢是否有人可以帮助我以角度方式来实现这一目标。

JS 代码:

var myApp = angular.module('myApp', ['ngRoute']);

myApp.controller('bookmarkCtrl', function($scope, $http) {

$scope.addThis = function() {
$http({
  url: "addbookmark.php",
  method: "POST",
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: $.param({
    bookmarktitle: $scope.bookmarktitle,
    bookmarkurl: $scope.bookmarkurl
  })
}).success(function(data, status, headers, config) {
    //refresh the table after success
}).error(function(data, status, headers, config) {
});
}
});

HTML

<div class="panel-body" ng-app="myApp" ng-controller="bookmarkCtrl">
<input ng-model="bookmarktitle" type="text" class="form-control" required>
<input  ng-model="bookmarkurl" type="text" class="form-control">
<button type="button" class="btn btn-default" ng-click="addThis();">Submit</button>


<table class="table table-responsive">
<thead>
  <tr>
    <th>...</th>
  </tr>
</thead>
<tbody>
   <!-- repeat row -->
    <tr>
      <td>
        <?php echo $row['bookmark_title'] ?>
      </td>
    </tr>
   <!-- repeat row -->
</tbody>
</table>
</div>

【问题讨论】:

标签: php angularjs


【解决方案1】:

@ismailvtl,angular 是一个客户端库,因此通常数据将通过来自客户端的 ajax 调用来填充。为了动态添加一行,控制器必须能够访问数据。

$scope.bookmarks = [];
$scope.getBookmarks = function() {
    $http.get('/bookmarks').then(function(response) {
        // should do validation here
        $scope.bookmarks = response.data
    }
}
$scope.getBookmarks();

然后,在你的 html 中,它应该是这样的

...
<tr ng-repeat="bookmark in bookmarks">
    <td>{{bookmark.bookmarktitle}}</td>
<tr>
...

然后,最后,在您的 addThis() 函数中:

$scope.addThis = function() {
    $http({
       url: "addbookmark.php",
       method: "POST",
       headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
       },
       data: $.param({
         bookmarktitle: $scope.bookmarktitle,
         bookmarkurl: $scope.bookmarkurl
       })
   }).success(function(data, status, headers, config) {
       var bookmark = { 
         bookmarktitle: data.bookmarktitle,
         bookmarkurl: data.bookmarkurl
        }
        $timeout(function() {
            $scope.bookmarks.push(bookmark)
        }
   }).error(function(data, status, headers, config) {
       // handle error here
   });
}

或者,您可以使用 ng-init 从 php 直接在视图中分配书签数组(类似于 ng-init="bookmarks=[{bookmarktitle: 'titlea',bookmarkurl: 'urla'},...]",其值由 php 提供。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 2012-12-17
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    相关资源
    最近更新 更多