使用angularJS提交具有两个相似的连续值的表单时,在控制台中收到错误

时间:2014-12-12 10:16:27

标签: javascript angularjs forms

我正在尝试使用Angular附加表单提交,但是当我提交多个连续的类似值时,我收到错误。例如,如果我提交“John”然后尝试提交另一个“John”,程序就会崩溃。有人可以向我解释一下吗?并提示如何修复它?

*也有人可以告诉我如何将结果附加到一行吗?

angular.module("displayText", [])
  .controller("submitText", function($scope) {
    $scope.outputArr = [];
    $scope.print = function() {

      $scope.outputArr.push($scope.inputText);
      $scope.inputText = '';
    };
  });
<html ng-app="displayText">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>

<body ng-controller="submitText">

  <div>

    <form method="get">
      <input type="text" name="post" ng-model="inputText" required/>
      <button ng-click="print(inputText)">Submit</button>
    </form>

    <div id="page">
      <p ng-repeat="text in outputArr">{{text}}</p>
    </div>

  </div>

</body>

</html>

2 个答案:

答案 0 :(得分:2)

ng-repeat无法处理重复值。

你必须改变

   <p ng-repeat="text in outputArr">{{text}}</p>

<p ng-repeat="text in outputArr track by $index">{{text}}</p>
对于一行可视化,

<p>元素到<span>

<span ng-repeat="text in outputArr track by $index">{{text}} </span>

以下是您问题的最简单解决方案:

&#13;
&#13;
angular.module("displayText", [])
  .controller("submitText", function($scope) {
    $scope.outputArr = [];
    $scope.print = function() {

      $scope.outputArr.push($scope.inputText);
      $scope.inputText = '';
    };
  });
&#13;
<html ng-app="displayText">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>

<body ng-controller="submitText">

  <div>

    <form method="get">
      <input type="text" name="post" ng-model="inputText" required/>
      <button ng-click="print(inputText)">Submit</button>
    </form>

    <div id="page">
      <span ng-repeat="text in outputArr track by $index">{{text}} </span>
    </div>

  </div>

</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

或者您可以将商品值包装到对象

angular.module("displayText", [])
  .controller("submitText", function($scope) {
  
    $scope.outputArr = [];
  
    $scope.print = function() {
      $scope.outputArr.push({
        text : $scope.inputText
      });
    };
  });
<html ng-app="displayText">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>

<body ng-controller="submitText">

  <div>

    <form method="get">
      <input type="text" name="post" ng-model="inputText">
      <button ng-click="print(inputText)">Submit</button>
    </form>

    <div id="page">
      <p ng-repeat="entry in outputArr">{{entry.text}}</p>
    </div>

  </div>

</body>

</html>