提交后的清晰表格

时间:2014-06-13 17:52:19

标签: javascript angularjs

我正在提交表单 - 并将内容添加到数组中,但无论何时将项目添加到数组中,它仍然绑定到表单。

我想添加项目,清除表单。像jquery的reset();

这是我的模板:

<div class="col-xs-12" ng-controller="ResourceController">
    <div class="col-md-4">
        <h3>Name</h3>
    </div>
    <div class="col-md-8">
        <h3>Description</h3>
    </div>
    <form class="form-inline" role="form" ng-repeat="item in resources">
        <div class="form-group col-md-4">
            <input type="text" class="form-control" value="{{ item.name }}"/>
        </div>
        <div class="form-group col-md-7">
            <input type="text" class="form-control" value="{{ item.description }}"/>
        </div>
    </form>
    <form class="form-inline" role="form" name="addResourceForm" ng-submit="addResource()">
        <div class="form-group col-md-4">
            <input type="text" class="form-control" name="name" ng-model="name" placeholder="Name"/>
        </div>
        <div class="form-group col-md-7">
            <input type="text" class="form-control" name="description" ng-model="description" placeholder="Description"/>
        </div>
        <div class="form-group col-md-1">
            <button type="submit" class="btn btn-default">Add</button>
        </div>
    </form>
</div>

我的控制员:

(function(){
    var app = angular.module('event-resources', []);
    app.controller('ResourceController', function($scope){
        $scope.addResource = function(){
            $scope.resources.push(this);
        }

        var defaultForm = {
            name : '',
            description: ''
        };

        $scope.resources = [
         {
            name: 'Beer',
            description: 'Kokanee'
         },
         {
            name: 'Pucks',
            description: 'Black Round Things'
         }
       ]
    });
})();

2 个答案:

答案 0 :(得分:1)

使用angular.copy()将项目数据复制到资源数组,然后您可以安全地清除项目数据。 angular.copy()制作对象的深层副本,这就是你想要的。


或者,这是一个更简单的方法,它不使用任何额外的方法调用:

$scope.addResource = function() {
  $scope.resources.push({
    name: $scope.name,      // recreate object manually (cheap for simple objects)
    description: $scope.description
  });
  $scope.name = "";         // clear the values.
  $scope.description = "";
};

答案 1 :(得分:0)

$scope.addResource = function(){
            $scope.resources.push(angular.copy(this));
            $scope.name="";
            $scope.description=""
        }

将副本推送到资源数组,并将名称和描述更改回&#34;&#34;