如何使用AngularJS,AJAX和XML在提交后向表中添加新行

时间:2016-11-05 14:11:19

标签: php angularjs ajax

我是AngularJS的新手,我正在尝试从JQuery转换为Angular。我知道我在.success中使用JQuery片段,但我非常怀疑它是否会起作用,但这应该会让你知道我想要做什么。在表单提交后,我似乎无法弄清楚如何在表中添加新行。我试图不断添加新的条目,但没有任何作用。如果你知道一个好的,简单的剪辑开始,将不胜感激。这是我到目前为止的代码:

HTML:

<table id="tblLogEntry">
                <tr id="tableheadings">
                    <th class="dateCol dateSize">Date</th>
                    <th class="trainingCol">Training</th>
                    <th class="successCol successSize">Success?</th>
                </tr>
            </table>

Angular:

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

logApp.controller('logController', ['$scope', '$http', function($scope, $http) {

    $scope.statuses = [
        {value:'Yes'},
        {value:'No'}
    ];

    $scope.logData = {};

    $scope.processLog = function(isValid) {

        if (isValid) {            
            $scope.isProcessing = true;
            $http({
                method: 'POST',
                url: 'LogEntryFile.php',
                data: $.param($scope.logData),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            })
                    .success(function(data) {
                        var parser = new DOMParser();
                        var parsedXML = parser.parseFromString(data, "text/xml");
                        var today = parsedXML.getElementsByTagName("today")[0].childNodes[0].nodeValue;
                        var log = parsedXML.getElementsByTagName("log")[0].childNodes[0].nodeValue;
                        var status = parsedXML.getElementsByTagName("status")[0].childNodes[0].nodeValue;
                        $('#tableheadings').after('<tr>\n\
                            <td>' + {{ logData.today }} + '</td>\n\
                            <td>' + {{ logData.log }} + '</td>\n\
                            <td>' + {{ logData.status }} + '</td></tr>');
            });
        }

    };

    $scope.clearFields = function() {
        $scope.logData = "";
    };

}]);

LogEntryFile.php:

$log = new Log();

$log->dateoflog = $_POST["today"];
$log->training = $_POST["log"];
$log->success = $_POST["status"];

$isLogValid = $log->validateLog();

if ($isLogValid) {    
   insertLog($log->dateoflog, $log->training, $log->success);

echo ('<logentry>'
        . '<today>' . $log->dateoflog . '</today>'
        . '<log>' . $log->training . '</log>'
        . '<status>' . $log->success . '</status>'
        . '</logentry>');
} else {
    header("Location: index.php");
}

1 个答案:

答案 0 :(得分:0)

使用AngularJS ng-repeat指令:

<table id="tblLogEntry">
    <tr id="tableheadings">
        <th class="dateCol dateSize">Date</th>
        <th class="trainingCol">Training</th>
        <th class="successCol successSize">Success?</th>
    </tr>
    <tr ng-repeat="row in rowArray">
        <td>{{row.today}}</td>
        <td>{{row.log}}</td>
        <td>{{row.status}}</td>
    </tr>           
</table>

ng-repeat指令将为名为rowArray的数组中的每个行对象编译并向DOM添加一行。