AngularJS:在对象中使用Controller As语法定位表单

时间:2016-08-01 16:50:16

标签: javascript angularjs forms angular-controller

注意:我确实在这里寻找解决方案,但没有人在对象中有额外的函数问题。

我的Angular JS应用程序中有一个表单:

<div ng-app="plunker">
  <div ng-controller="PMTController as pmt">
   <form name="myForm">
    <div class="form-group">
     <input type="text" class="form-control" />
    </div>
    <button class="btn btn-primary" ng-click="pmt.search.resetSearchForm()">Reset</button>
   </form>
 </div>
</div>

此外,我有一个带有对象的控制器:

app.controller('PMTController', function($log) {
  var _this = this;

  _this.search = {
    resetSearchForm: function () {
     $log.debug('test');
     // how to target the form?
   }
 };
})

我的ng-click工作,因为log.debug工作。但是没有多少调整来定位表单以便我可以重置整个事物(清空所有字段)。

我可以做$window.myForm.reset();但我怎么能从角度做到这一点?

请注意,我的主要问题是如何从resetSearchForm对象的search函数中正确定位表单

注意我尝试将表单名称更改为pmt.myFormpmt.search.myForm,但无效。

我尝试$setPristine$setUntouched(),但他们似乎没有清除这些字段。

我知道我可以指定一个模型并将其分配给所有表单控件,但这是针对原型的,所以我宁愿进行简单的重置。

我画了一支笔:https://codepen.io/smlombardi/pen/YWOPPq?editors=1011#0

2 个答案:

答案 0 :(得分:0)

以下是我对您的codepen的看法,希望能够解决这个问题:

https://codepen.io/watsoncn/pen/YWOXqZ?editors=1011

说明:

Angular的文档提供了一个&#34; Form Reset&#34;按钮,但您可以在提交后应用相同的逻辑重置:

Documentation: https://docs.angularjs.org/guide/forms

带有一个掠夺者:

Live Example: https://plnkr.co/edit/?p=preview

该示例显示了使用Angular的copy方法,该方法创建了作为参数传递的任何内容的深层副本,并将其分配给放置在特定输入字段上的ng模型。在这种情况下,他们只是传递一个空的主对象。

您需要确保在输入中添加ng-model属性,然后创建一个可在提交后运行的重置功能。另一个常见选项是简单地将每个输入的ng-model设置为提交函数中的空字符串,例如$scope.inputModel = ""

这是你所希望的吗?我可能误解了这个问题。如果仍然存在困惑,我将很高兴再次采取行动。

答案 1 :(得分:0)

要在控制器中获取表单,只需要以这种方式命名表单:

<form name="pmt.myForm">

这是一个完整的演示

(function() {
  "use strict";

  angular
    .module('plunker', [])
    .controller('PMTController', PMTController);

  PMTController.$inject = ['$log'];

  function PMTController($log) {
    var _this = this;
    _this.model = {};
    
    _this.search = {
      resetSearchForm: function() {
        console.log(_this.myForm); // -> Form reference
        _this.model = {};
      }
    };
  }
})();
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
</head>

<body ng-controller="PMTController as pmt">
  <div class="col-md-12">
    <form name="pmt.myForm">
      <div class="form-group">
        <input type="text" ng-model="pmt.model.example" class="form-control" />
        <input type="text" ng-model="pmt.model.example2" class="form-control" />
        <input type="text" ng-model="pmt.model.example3" class="form-control" />
      </div>
      <button class="btn btn-primary" ng-click="pmt.search.resetSearchForm()">Reset</button>
    </form>
    <hr> All fields:
    <pre ng-bind="pmt.model | json"></pre>
  </div>
</body>

</html>