AngularJS Directive templateUrl returns 400 though file URL loads

余生颓废 提交于 2019-12-30 18:47:13

问题


I have a basic directive in a MVC 5 Layout Page with a directive for searching. My problem is that the templateUrl cannot be loaded (400 error). If I enter the URL directly into the browser, I can load the html page without difficulty or error. I cannot find out why the AJAX call to load the page is failing.

Chrome Debugger

This is the HTML page loading in Chrome

app.js

(function() {
     var app = angular.module("mainApp");

     app.directive("basicSearch", function() {
        return {
            templateUrl: 'app/directives/basic-search.html',
            controller: function($scope, search) {
                $scope.keyword = '';
                $scope.exact = false;
                $scope.submitSearch = function () {
                    search.searchByKeyword($scope.keyword, 0, $scope.exact);
                }
            }
        }
     });
}());

basic-search.html

<div>
    <input type="search" ng-model="keyword" name="keyword" />
    <button type="submit" ng-click="submitSearch()"></button>
    <input type="checkbox"ng-model="exact" name="exact" />
    <label for="exact">Exact Match?</label>
</div>

_Layout.cshtml

<html>
     <head>
     <base href="@Request.ApplicationPath" />
     <!--- JS & CS References -->
     <title></title>
     </head>
     <body ng-app="mainApp">
     <!-- Other stuff -->
     <basic-search></basic-search>
     <!-- More other stuff -->
     @RenderBody()
     </body>
</html>

EDIT Here is the successful request (via browser):

and here is the one that fails (via Angular directive):


回答1:


The IE bug that Chris is referring to is a caching error that allows old content to be re-served when using angular's $http and IE.

I've written about the subject here: http://benjii.me/2014/07/ie-is-caching-my-angular-requests-to-asp-net-mvc/

A better fix than removing the bug-fix code is to fix it. Use the following instead:

//initialize get if not there
if (!$httpProvider.defaults.headers.get) {
    $httpProvider.defaults.headers.get = {};
}

//disable IE ajax request caching
$httpProvider.defaults.headers.get["If-Modified-Since"] = "Fri, 01 Jan 2010 00:00:00 GMT";



回答2:


I solved it. It seems someone added the following to the module config as an attempt to resolve an IE bug (surprise, surprise):

//initialize get if not there
if (!$httpProvider.defaults.headers.get) {
    $httpProvider.defaults.headers.get = {};
}

//disable IE ajax request caching
$httpProvider.defaults.headers.get["If-Modified-Since"] = "0";

I removed it, cleared out my cache and it's working fine.



来源:https://stackoverflow.com/questions/28416551/angularjs-directive-templateurl-returns-400-though-file-url-loads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!