the use of this vs $scope in a POST request
This question already has an answer here:
You need to realize that Javascript has multiple scopes and that the this
keyword refers to the scope you are operating in.
Then, like mentioned by @Henri S, you should also realize the scope of your controller, which is a JavaScript contructor function, is not the same as the $scope
you are using inside. The $scope used by Angular is an object associated with a controller, which is really a viewmodel to begin with. Your HTML, under the control of a certain controller can 'access' this object. If you create chains of controllers, the $scope will prototypically inherit.
If we apply this to your code:
var app = angular.module('TM', []);
app.controller('tableController', function($scope, $http){
var self = this; //We capture a reference/value of the scope of your controller
this.formData = {};
this.currentDataObject : {restURL: "../protocols"}
// Define process for submitting form
this.processForm = function() { //Here begins a new javascript scope
console.log('Inside processForm method');
$('#addEntry').modal('hide');
console.log(self.formData); // this will refer to the this.formdata
$http({
method : 'POST',
url : self.currentDataObject.restURL,
data : JSON.stringify(self.formData),
headers : {
'dataType' : "json",
'contentType' : "application/json"
}
})
.success(function(data) {
console.log('Success: ' + data);
//Empties the object after the POST request is done...
self.formData = {}
})
.error(function(data){
console.log('Error ' + data);
});
};
});
$scope != this.
'this' is context sensitive, related to his 'direct parent'.
$scope isn't needed, if you use the 'controller as' syntax.
But, if you still want to use $scope, use $scope.formData in your controller.
链接地址: http://www.djcxy.com/p/77796.html