John Pangilinan John Pangilinan - 1 year ago 83
AngularJS Question

AngularJS templateUrl via POST METHOD

i have a directive that returns a template from a url

app.directive('mytemplate', function(){
return {
templateUrl '/my/template/

Request URL:
Request Method:GET
Status Code:200 OK
Remote Address:

however the request method used is GET by default. How could change it to POST instead?


i think your solution cannot work, i cant return the html because it is async.

app.directive('mytemplate', function(){
return {
templateUrl : function(elem, attr){
$.post('/test/my/template', null, function(response) {
//how could i return the response?

Answer Source

You can override angular's $templateRequest service, which is responsible for fetching the templates.

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 ${ 
          var result =;
          // Cache the result
          $templateCache.put(templateUrl, result);
          return result;
      } else {
        return $q.resolve(tpl);

With this in your app, the original directive code

app.directive('mytemplate', function(){
  return {
    templateUrl '/my/template/'

should send a POST request instead of GET.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download