John Pangilinan
John Pangilinan

Reputation: 1031

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?
             });
        }
    }
});

UPDATE:

I found another solution which does not need to override the $templateRequest service:

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

Upvotes: 0

Views: 586

Answers (1)

noppa
noppa

Reputation: 4066

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.

Upvotes: 3

Related Questions