首页 > 解决方案 > AngularJS ng-submit 以表格形式打印结果

问题描述

它的目的是我可以输入一些数据并在表格中{{urname}}{{urcm}}表格内部进行更新。但是,表达式是行不通的。

在此处输入图像描述

此外,当我提交新评论时,我无法在表格中打开新行。所有数据打包在一起。

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

myApp.controller('TableFilterCtrl', ['$scope', function($scope) {
  $scope.urname = [];
  $scope.urcm = [];
  $scope.uname = '';
  $scope.ucm = '';
  $scope.submit = function() {
    if (!!$scope.uname, !!$scope.ucm) {
      $scope.urname.push($scope.uname);
      $scope.urcm.push($scope.ucm);
    }
    $scope.uname = '';
    $scope.ucm = '';
  }
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<html ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>Demo</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
  <script src="js/control.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="css/hp.css">
</head>

<body>
  <form ng-submit="submit()" ng-controller="TableFilterCtrl">
    <label>Name: </label>
    <input type="text" ng-model="uname" name="uname" placeholder="Enter your name." />
    <label>Comments on mv: </label>
    <input type="text" ng-model="ucm" name="ucm">
    <input type="submit" id="submit" value="submit" />

    <div>
      <table>
        <tr>
          <td>Name</td>
          <td>Comments</td>
        </tr>
        <tr>
          <td>{{urname}}</td>
          <td>{{urcm}}</td>
        </tr>
      </table>
    </div>
  </form>
</body>

标签: angularjsexpressionng-submit

解决方案


只需稍微更改逻辑并使用 ng-repeat,我建议如下:

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

myApp.controller('TableFilterCtrl', ['$scope', function($scope) {
  $scope.ur = [];
  $scope.uname = '';
  $scope.ucm = '';
  $scope.submit = function() {
    if (!!$scope.uname, !!$scope.ucm) {
      $scope.ur.push({
        name: $scope.uname,
        cm: $scope.ucm
      });
    }
    $scope.uname = '';
    $scope.ucm = '';
  }

}]);
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <meta charset="utf-8">
  <title>Demo</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
</head>

<body>
  <form ng-submit="submit()" ng-controller="TableFilterCtrl">
    <label>Name: </label>
    <input type="text" ng-model="uname" name="uname" placeholder="Enter your name." />
    <label>Comments on mv: </label>
    <input type="text" ng-model="ucm" name="ucm">
    <input type="submit" id="submit" value="submit" />

    <div>
      <table>
        <tr>
          <td>Name</td>
          <td>Comments</td>
        </tr>
        <tr ng-repeat="u in ur">
          <td>{{u.name}}</td>
          <td>{{u.cm}}</td>
        </tr>
      </table>
    </div>
  </form>
</body>


推荐阅读