Angular Form Resetting with Ajax Callbacks

2019-09-12 10:44发布

问题:

I have a basic form with an Angular $save action run on submit:

app.controller 'MyThingCtrl', ($scope, MyThing) ->
    this.addThing = ->
      new MyThing(this.thing).$save(
        (data) ->
          console.log 'New Thing Saved'
          $scope.things.push data
          this.thing = {}
        ,(err) ->
          console.log 'Error: ' + err
        )

The expectation is that the form for this.thing will be reset on success, but it isn't, as the this no longer refers to what it did before.

回答1:

While the scope of this is changed inside the callback, the variable thing is available via the $scope variable provided by Angular:

app.controller 'MyThingCtrl', ($scope, MyThing) ->
    this.addThing = ->
      new MyThing(this.thing).$save(
        (data) ->
          console.log 'New Thing Saved'
          $scope.things.push data
          $scope.thing = {}
        ,(err) ->
          console.log 'Error: ' + err
        )