通过POST方法
问题描述:
AngularJS templateUrl我有从URL通过POST方法
app.directive('mytemplate', function(){
return {
templateUrl '/my/template/
}
});
Request URL:http://127.0.0.1/test/my/template/
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:80
然而使用的请求的方法是通过默认GET返回的模板的指令。怎么可以改为POST呢?
@Developer
我认为您的解决方案不能工作,我不能返回HTML,因为它是异步。
app.directive('mytemplate', function(){
return {
templateUrl : function(elem, attr){
$.post('/test/my/template', null, function(response) {
//how could i return the response?
});
}
}
});
UPDATE:
我发现了另一个解决方案,它并不需要覆盖$templateRequest
服务:
app.directive('myTemplate', function($http, $compile){
return {
link: function (scope, element, attrs) {
$http.post('/my/template/').success(function(res){
element.html(res.data);
$compile(element.contents())(scope);
});
}
}
});
答
您可以覆盖角的$templateRequest服务,这是负责提取模板。
app.config(['$provide', function($provide) {
$provide.decorator('$templateRequest', ['$http', '$templateCache', '$q', '$delegate',
function($http, $templateCache, $q, $delegate) {
// Return a function that will be
// called when a template needs to be fetched
return function(templateUrl) {
// Check if the template is already in cache
var tpl = $templateCache.get(templateUrl);
if (tpl === undefined) {
if (false) {
// If you only sometimes want to use POST and sometimes you want
// to use GET instead, you can check here if the request should
// be normal GET request or not. If it should, just use $delegate
// service and it will call the original fetcher function.
return $delegate(templateUrl);
}
// Make your POST request here
return $http.post(templateUrl).then(function(res){
var result = res.data;
// Cache the result
$templateCache.put(templateUrl, result);
return result;
});
} else {
return $q.resolve(tpl);
}
};
}]);
}]);
有了这个应用程式后,原来的指令代码
app.directive('mytemplate', function(){
return {
templateUrl '/my/template/'
}
});
应该发送POST请求,而不是GET的。
+0
谢谢!我永远无法解决这个问题。 –
这是因为我使用了一个框架(Phalcon),并且我有一个条件,如果方法是POST,它将只返回当前操作的视图,其中作为GET,它将返回视图+主视图,我不想包括。 –
我的不好,我看错了你的问题。 – Developer
我真的需要这样做,我这样做,我不能通过url中的GET方法访问视图。所以如果我访问'http:// localhost/test/my/template',我可以单独访问我正在阻止的视图。我只想通过POST访问视图。 –