从AngularJS中的动态表单中清除字段

时间:2017-03-07 09:56:54

标签: javascript angularjs arrays object

这是我的angularjs代码:



function addController($scope, $http) {
  $scope.update = [];
  $scope.properties = [];

  $scope.addProperties = function(property) {
    $scope.properties.push({});
  }
  $scope.add = function() {
    $scope.update.push({
      "tableName": $scope.tableName,
      "name": $scope.name,
      "properties": $scope.properties
    });
    $scope.tableName = undefined;
    $scope.name = undefined;

  }

}

<!DOCTYPE html>
<html ng-app>

<head>
  <title></title>
  <meta charset="utf-8" />
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>

<body ng-controller="addController">

  <div class="col-sm-10">
    <label class="control-label">TableName:</label>
    <input type="text" class="form-control" ng-model="tableName" /><br />
  </div>

  <div class="col-sm-10">
    <label class="control-label">Name:</label>
    <input type="text" class="form-control" ng-model="name" /><br />
  </div>

  <div class="col-sm-10">
    <label class="control-label">Properties:</label>
    <fieldset ng-repeat="property in properties track by $index">
      <label class="control-label">Column Name:</label>
      <input type="text" class="form-control" ng-model="property.columnName" /><br />
      <label class="control-label">Name:</label>
      <input type="text" class="form-control" ng-model="property.name" /><br />

    </fieldset>
    <button class="btn btn-default" ng-click="addProperties()">Add Properties</button>
  </div>
  <div class="col-sm-10">
    <input type="submit" ng-click="add()" />
    <pre>{{update[0]|json}}</pre>
  </div>
</body>

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

此处ColumnName和name是通过单击addProperties按钮添加的动态文本框。

我的问题在于add()函数。一旦表单元素被推送更新(数组)我想要清除表单元素。 tableName和name被指定为undefined,因为它们不是动态的并且工作正常。你能帮我分配columnName和name字段为null或undefined。(特别注意:赋值为null或undefined只能影响视图。更新数组中推送的值不得更改)

2 个答案:

答案 0 :(得分:0)

将addProperties方法更新为此。

    $scope.addProperties = function (property) {
        $scope.properties.push(property);
        $scope.property = {name:"", columnName:""}
    }

这将重置视图中的属性,我也不会在视图中的道具上使用ng重复,因此您只需要编辑一组输入。

答案 1 :(得分:0)

您应该在推送后清除$scope.addProperties = function(property) { $scope.properties.push(property); property = {"name": null, "columnName": null}; } 对象:

undefined

注意:避免使用{{1}}来清理对象,因为它表示属性是......未定义!