http调用位于指令内部的控制器内部

http call inside of a controller which is inside of a directive

本文关键字:内部 控制器 指令 调用 于指令 http      更新时间:2023-09-26

我有一个名为TestServlet.java的servlet,它返回一些数据(返回什么并不重要,只是一些文本)。

这是我正在创建的ng指令:

(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"
        }
    })
})();

这是test.html文件:

<div>
    this is a test partial html
    <br>
    <input type="text" ng-model="at.test" />
    {{at.test}}
    <br>
    {{at.diranswer}}
    <br>
    {{at.direrror}}
</div>

我无法将servlet返回的文本分配给at.diranswer。你能帮我一下吗?

谢谢,Turik

$http回调中的this的值不同于diranswer所在的this。所以,当你在回调中设置它时,你就是在一个完全不同的对象上设置它。在发出呼叫之前,您需要保存值:

var self = this;
$http(req).then(function(response) {
     self.diranswer += response.data;
     console.log(self.diranswer);
}, function(response) {
     self.direrror = response.data;
});