简体   繁体   English

AngularJS包含位于文件夹中的文件

[英]AngularJS include a file located in a folder

When I do 当我做

/sites/all/themes/theme/js/controller.js /sites/all/themes/theme/js/controller.js

$scope.template = 'partials/tpl.html'

/sites/all/themes/theme/js/index.html /sites/all/themes/theme/js/index.html

<div ng-include='template'></div>

/sites/all/themes/theme/js/partials/tpl.html /sites/all/themes/theme/js/partials/tpl.html

<b>Ho boy!</b>

I basically moved everything related to angular into js folder. 我基本上把与angular相关的所有内容都移到js文件夹中。

It returns localhost/partials/tpl.html while I need localhost/sites/all/themes/js/partials/tpl.html . 它返回localhost/partials/tpl.html而我需要localhost/sites/all/themes/js/partials/tpl.html How do I solve that without using an absolute path? 如何在不使用绝对路径的情况下解决这个问题?

I solved this issue using $httpProvider.interceptors. 我使用$ httpProvider.interceptors解决了这个问题。 The following prepends 'myAppDirectory' to ALL requests. 以下将'myAppDirectory'添加到所有请求之前。

$httpProvider.interceptors.push(function($q) {
    return {
     'request': function(config) {
         config.url = 'myAppDirectory/'+config.url;
         return config;
      },
    };
  });

A regular ng-include, such as: 常规ng-include,例如:

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

Will load myAppDirectory/user/info.html 将加载myAppDirectory / user / info.html

You probably want to make some exceptions. 你可能想做一些例外。 In my case: 就我而言:

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

Add a <base href="/sites/all/themes/theme/js/"> at the top of your <head> element inside index.html . index.html内的<head>元素顶部添加<base href="/sites/all/themes/theme/js/">

<html>
  <head>
    <base href="/sites/all/themes/theme/js/">
    ...

Reference 参考

Relative links 相关链接

Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (<base href="/my-base">) or you must use absolute urls (starting with /) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application. 请务必检查所有相关链接,图像,脚本等。您必须在主html文件(<base href =“/ my-base”>)的头部指定url base,或者必须使用绝对URL(从/)到处都是因为相对网址将使用文档的初始绝对网址解析为绝对网址,这通常与应用程序的根目录不同。

Running Angular apps with the History API enabled from document root is strongly encouraged as it takes care of all relative link issues. 强烈建议使用从文档根目录启用历史记录API运行Angular应用程序,因为它会处理所有相关链接问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM