无法在Angular中的ngDialog模板中清除表单输入值

时间:2015-12-09 00:08:03

标签: javascript html angularjs ng-dialog

我正在使用ngDialog [https://github.com/likeastore/ngDialog]创建一个模态,我有一个基本形式,当我点击一个按钮时发出一个POST请求。在同一个按钮单击,我希望表单输入清除。通常,您可以执行$scope.valueOfNgModel = "";之类的操作,但在这种情况下这不起作用。此外,ngDialog范围与它实例化控制器的$ scope相同。

这里是ngDialog实例化:

$scope.addStudents = function() {
  ngDialog.open({
    template: 'addStudents',
    scope: $scope
  });
};

这是ngDialog模板:

<script type="text/ng-template" id="addStudents">
  <h1> Add Students to Your Class </h1>

  <form ng-model="myForm" ng-submit="addNewStudent(newStudent)">
    <input ng-model="newStudent.firstName" placeholder="First Name">
    <input ng-model="newStudent.lastName" placeholder="Last Name">
    <input ng-model="newStudent.email" placeholder="Email">
    <input ng-model="newStudent.image" placeholder="imageUrl">
    <h3> Note: Student Password by Default will be Firstname.lastname </h3>

    <button class="ngdialog-button 
        ngdialog-button-primary" 
        type="submit">Add Student
    </button>
</form>

</script>

以下是我要清除所有输入字段的fomr提交(或按钮点击)上运行的功能:

$scope.addNewStudent = function(student) {

  var newUserToAdd = {
    firstName: student.firstName,
    lastName: student.lastName,
    teacher: false,
    email: student.email,
    password: student.firstName + '.' + student.lastName,
    classesBelongTo: [$scope.currentClassId],
    image: student.image
  };

  userService.postNewUser(newUserToAdd)
    .then(function(response) {
      $scope.loggedInUser = response.data;
    })
    console.log("this is $scope.newStudent", $scope.newStudent); //this is undefined - I'm not sure why

    $scope.newStudent = {}; //I tried this to clear it out
    $scope.$apply(); //I tried this to no avail
}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

您可以为表单命名,然后致电$scope.yourFormName.$setPristine();

例如:Fiddle