AngularJS - the use of this vs $scope in a POST request
本问题已经有最佳答案,请猛点这里访问。
我读过几篇关于使用
下面是一个代码示例,我在其中执行
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | var app = angular.module('TM', []); app.controller('tableController', function($scope, $http){ //Empty object that gets filled with data and sent as a POST request. this.formData = {}; // Define process for submitting form //TODO: FIND OUT THE DIFFERENCE BETWEEN $SCOPE AND THIS this.processForm = function() { console.log('Inside processForm method'); $('#addEntry').modal('hide'); console.log($scope.formData); //If I use this here - the object is empty $http({ method : 'POST', url :'../protocols', data : JSON.stringify($scope.formData), headers : { 'dataType' :"json", 'contentType' :"application/json" } }) .success(function(data) { console.log('Success: ' + data); //Empties the object after the POST request is done... $scope.formData = {} }) .error(function(data){ console.log('Error ' + data); }); }; }); |
您需要认识到javascript有多个作用域,并且
然后,正如@henri s所提到的,您还应该认识到控制器的作用域,它是一个javascript构造函数,与您在内部使用的
如果我们将此应用于您的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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); }); }; }); |
$范围!=这个。
"this"与上下文相关,与"direct parent"相关。
如果使用"controller as"语法,则不需要$scope。
但是,如果您仍然想使用$scope,请在控制器中使用$scope.formdata。