使用angularjs,php和mysql后$ http帖子后刷新表

时间:2016-01-26 16:34:40

标签: php angularjs

我需要刷新表格,以便在从$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>

1 个答案:

答案 0 :(得分:0)

@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: $scope.bookmarktitle,
         bookmarkurl: $scope.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提供。