Form is not clearing values in success function of

2019-09-12 10:26发布

问题:

I have a form in that, I am using angualr.js. I am binding input values to angular variables. After submitting form, in success function of $.ajax, I am assigning empty values to these variables, but I am seeing same values in form instead of empty strings. Below is my form code,

 <form name="addForm"  ng-submit="outClear()">
      <table>
       <tr>
          <td> <label>Title</label></td>
          <td> <input type="text" id="idTitle" ng-model="Title"/> </td>
        </tr>
        <tr>
           <td> <label>Description</label></td>
           <td> <textarea id="idDescription" name="desc" ng-model="Description" ></textarea> </td>
        </tr>
        <td><input type="submit" class="btn btn-default" value="Add" />  </td>
         <td></td>
         </tr>
        </table>
</form>

Below is my java script code,

var MyApp = angular.module("MyApp", []);
  MyApp.controller("TicketCntrl", function ($scope) {
 $scope.outClear = function () {
    var Title = $scope.Title;
    var Description = $scope.Description;

    var Ticket = {
        "Title": String(Title),
        "Description": String(Description),
    };

    $.ajax({
        type: "POST",
        url: "/Home/Add",
        data: Ticket,
        success: function (data, status) {
        alert('In success');
            $scope.clear();
        },
        error: function (status, error) {
        }
    });


};
$scope.clear = function () {
    $scope.Title = '';
    $scope.Description = '';
    alert('In clear');
  }
 }

It is going to success function and showing 'In Success' message and going to clear() and assigning '' values to $scope.Title and $scope.Description but in text box and text area I am seeing same values which I have entered.

one more thing I tried, instead of outClear(), I directly call clear() after submitting. Then it is perfectly working(all form values getting empty).

Please let me know where I am doing wrong.

回答1:

Don't mix angular with jQuery for manipulating scope variables, it will messed up with digest cycle of angular. It will not run digest cycle if you do update scope variable from jQuery.

You need to run digest cycle by calling $apply() over $scope after your method clear() in Ajax success to fix it issue quickly, but ideally I wouldn't prefer go for this approach.

Instead do use $http instead of $.ajax.