2016-11-14 132 views
0

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

這是因爲我使用了一個框架(Phalcon),並且我有一個條件,如果方法是POST,它將只返回當前操作的視圖,其中作爲GET,它將返回視圖+主視圖,我不想包括。 –

+0

我的不好,我看錯了你的問題。 – Developer

+0

我真的需要這樣做,我這樣做,我不能通過url中的GET方法訪問視圖。所以如果我訪問'http:// localhost/test/my/template',我可以單獨訪問我正在阻止的視圖。我只想通過POST訪問視圖。 –

回答

2

您可以覆蓋角的$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

謝謝!我永遠無法解決這個問題。 –