2016-01-26 27 views
1

我需要刷新表格以顯示從$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> 
+0

LMGTFY:https://www.google.co.uk/search?q=angular+add+table+row –

+0

[如何使用angularjs將動態行添加到表中](http://stackoverflow.com)/questions/21427089/how-to-add-dynamic-row-to-a-table-using-angularjs) –

回答

0

@ismailvtl,角是一個客戶端庫,所以通常數據將通過從一個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> 
... 

然後,最後,在你的前頁()函數:

$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 
    }); 
} 

或者,你可以將書籤陣列直接在php的視圖中使用ng-init(類似於ng-init="bookmarks=[{bookmarktitle: 'titlea',bookmarkurl: 'urla'},...]",值由php提供)

+0

你有沒有得到這個工作,@ismailvtl? – Beartums