John Pangilinan John Pangilinan - 26 days ago 8
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:http://127.0.0.1/test/my/template/
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:80


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

@Developer

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

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 $http.post(templateUrl).then(function(res){ 
          var result = res.data;
          // 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.