Angularjs 修改ng include指令

Angularjs 修改ng include指令,angularjs,angularjs-ng-include,Angularjs,Angularjs Ng Include,如果我在某个自定义位置托管angular应用程序。http://localhost/collosys然后我必须更改所有ng include,以使所有地址都具有“/collosys/”,因为我使用绝对地址引用任何html文件 我现在就是这样做的 <script> var baseUrl = document.location.pathname; document.write('<base href="' + document.location.pathname +

如果我在某个自定义位置托管angular应用程序
。http://localhost/collosys
然后我必须更改所有ng include,以使所有地址都具有“/collosys/”,因为我使用绝对地址引用任何html文件

我现在就是这样做的

<script>
    var baseUrl = document.location.pathname;
    document.write('<base href="' + document.location.pathname + '" />');
</script>

var baseUrl=document.location.pathname;
文件。写(“”);
然后在重写中包含标记

FROM: <div data-ng-include="'/Generic/csgrid/grid-buttons.html'"></div>
TO: <div data-ng-include=" baseUrl + 'Generic/csgrid/grid-buttons.html'"></div>
来自:
致:
我是否可以修改ng include标记本身,以便它可以在所有地址前面加上主机地址

编辑


我在某个地方读到angularjs指令是可扩展的,有没有关于如何扩展angularjs ngInclude指令的示例??任何例子???

是的,你可以,但我会写我自己的ng include。如果您尝试升级angular,您只需覆盖更改。

修改标记中的
head
标记:

<head>
  <base href="collosys" />
</head>

如前所述,您有几个选项:

  • 更改源代码(也称为monkey patching)-不推荐,需要高维护,并使其他人无法读取您的代码

  • 使用decorator,它允许您获取ngInclude指令并对其进行更改。decorator通常用于扩展\更改第三方LIB,但缺点是您必须替换ngInclude的整个编译函数,这大约需要60行代码来交换一个小前缀。更不用说,如果angular改变了ngInclude的工作方式,那么您将使用它的一个不受欢迎或损坏的版本

  • 编写自己的包装指令,该指令将调用ngInclude。从现在起,您将拥有myInclude:

    angular.module('myApp').directive('myInclude', [function () {
        var baseUrl = 'collosys';
        return {
            replace: true,
            scope: {
                myInclude: '@'
            },
            template: '<div ng-include="' + baseUrl + '{{myInclude}}"></div>'
        };
    }]);
    
    angular.module('myApp')。指令('myInclude',[function(){
    var baseUrl='collosys';
    返回{
    替换:正确,
    范围:{
    myInclude:“@”
    },
    模板:“”
    };
    }]);
    

  • 我使用$httpProvider.interceptors解决了这个问题。以下内容将“myAppDirectory”前置到所有请求

    $httpProvider.interceptors.push(function($q) {
        return {
         'request': function(config) {
             config.url = 'myAppDirectory/'+config.url;
             return config;
          },
        };
      });
    
    常规ng包括,例如:

    <div ng-include="'user/info.html'">
    

    我已经在写基标签了。。。我已经写过这个问题了,是不是行得通?我不确定在客户端设置值时它是否行得通(在DOM呈现之后)我正在服务器上设置该值。使用此方法是我发现的将模板缓存中的某些ng include'd项列入黑名单的唯一方法:为不应由$templateCache缓存的文件在config.url的末尾添加一个像“?123”这样的随机url参数。我尝试了此方法,但在新指令的模板上失败了
    .directive('viewInclude',[function(){var baseUrl='fams360frontend/views';返回{replace:true,作用域:{viewInclude:'@'},模板:'};}])
    
      $httpProvider.interceptors.push(function() {
        return {
         'request': function(config) {
             // ignore api calls and ui-bootstrap templates.
             if (config.url.indexOf('api')==-1 && config.url.indexOf('template')==-1) {
               config.url = 'myAppDirectory/'+config.url;
             }
             return config;
          },
        };
      });