【问题标题】:angularjs -how to clear the form data from a clear button outside sitting outside the formangularjs - 如何从表单外的清除按钮清除表单数据
【发布时间】:2016-07-08 23:29:41
【问题描述】:

我有一个带有提交按钮的表单,效果很好。但是,我需要从页面右上角的表单外部的清除按钮清除表单数据。清除按钮存在于父控制器中,位于右上角标题中的表单上方。从清除按钮发送的表单始终显示为未定义,这是因为清除按钮不是表单的一部分。

如何传递相同的表单实例来清除?如何清除数据?如果这是一个设计问题,我仍然需要解决方法。

这是我为模仿而创建的小提琴。任何帮助将不胜感激。

https://jsfiddle.net/SobDan/vj67rtb2/

<div ng-app>

<div class="col-md-10">
  <h2>Todo</h2></div>
<div class="col-md-2">
  <button class="btn pull-right" ng-click="clear(TodoForm)"> Close</button>

</div>
<br>
<div ng-controller="TodoCtrl">

  <form name="TodoForm" ng-submit="addTodo()" name="testForm">
    <input type="text" ng-model="todoText" size="30" placeholder="add new todo here">
    <input class="btn-primary" type="submit" value="add">

  </form>

</div>

function MainCtrl($scope) { 

$scope.clear = function(form) {
    alert(form); // the form is undefined
    if (form.$dirty)
      form.setPristine(); // clean this form
    else
      alert("form not dirty");
  };
};

function TodoCtrl($scope) {

  $scope.todoText = "test";
  $scope.addTodo = function() {
    alert("Submitted");
    $scope.todoText = "";
    // submit logic works fine
  };
}

【问题讨论】:

    标签: angularjs forms reset form-data


    【解决方案1】:

    您应该使用$broadcast 在控制器之间进行通信,而不是尝试访问超出范围的表单。

    这里是fiddle和下面的解释

    $broadcast 函数用于向所有子 $scope 广播事件。任何有兴趣的孩子$scope 都可以使用$on 函数注册监听事件。此功能用于在控制器之间进行通信。

    在您的情况下,我们通过从$rootScope 广播名为 clearForm 的事件来发出清除表单的信号。 TodoCtrl $scope 监听事件 clearForm 将接收到清除表单字段的信号。

    app.controller("MainCtrl", function($scope, $rootScope) {
      $scope.clear = function(form) {
        $rootScope.$broadcast("clearForm");
      };
    });
    
    app.controller("TodoCtrl", function($scope) {  
      $scope.$on("clearForm", function() {
        if ($scope.testForm.$dirty) {
          $scope.testForm.$setPristine();
          $scope.todoText = "";
        } else {
          alert("form not dirty");
        }   
      });
    });
    

    AngularJS 1.1.x +

    $scope.form.$setPristine() 仅适用于 AngularJS 版本 1.1.x。

    $setPristine() 只会将表单状态设置为原始状态,不会清除表单字段。您需要通过取消将反映在屏幕上的 $scope 变量来手动清除它。

    if ($scope.testForm.$dirty) {
      $scope.testForm.$setPristine();
      $scope.todoText = "";
    }
    

    AngularJS 1.0.x +

    $setPristine 功能在 1.0.x 版本中不可用。

    您问题中的示例Fiddle 似乎配置为1.0.x

    在 1.0.x 中,您只需清除 $scope 变量

      $scope.$on("clearForm", function() {
          $scope.todoText = "";
      });
    

    【讨论】:

    • 也可以从$scope广播,因为其他控制器是孩子
    • kalyan 我可以使用表单清除所有字段而不使用 $setPristine
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多