Reputation: 211
I a have a servlet called TestServlet.java which returns some data (not important what it returns, just some text).
Here's the ng directive I'm creating:
(function() {
var aMod = angular.module('aMod', []);
aMod.directive('aDir', function($http) {
return {
restrict : 'E',
templateUrl : "test.html",
controller : function() {
this.test = 'this is a test variable';
this.diranswer = 'Test: ';
this.direrror;
var req = {
method : 'POST',
url : '/test1/TestServlet',
params : {
p1 : 'test1',
p2 : 'test2'
}
};
$http(req).then(function(response) {
this.diranswer += response.data;
console.log(this.diranswer);
}, function(response) {
this.direrror = response.data;
});
},
controllerAs : "at"
}
})
})();
and here's the test.html file:
<div>
this is a test partial html
<br>
<input type="text" ng-model="at.test" />
{{at.test}}
<br>
{{at.diranswer}}
<br>
{{at.direrror}}
</div>
I'm not being able to assign to at.diranswer the text returned by the servlet. Could you please help me out with this?
Thanks, Turik
Upvotes: 1
Views: 38
Reputation: 9597
The value of this
inside the $http
callback is different than the this
on which diranswer
exists. So, when you set it in the callback, you're setting it on a totally different object. You need to save off the value before issuing the call:
var self = this;
$http(req).then(function(response) {
self.diranswer += response.data;
console.log(self.diranswer);
}, function(response) {
self.direrror = response.data;
});
Upvotes: 2