情况是这样的。我有一个指令,它取决于 templateUrl。

该指令看起来像这样:

angular.module('foo')
.directive('bar', function(){
  return {
    restrict: 'E',
    replace: true,
    templateUrl: '/foo/bar.html',
    controller: 'fooController',
    require: '^ngModel',
    scope: {
      onSuccess: '&'
    }
  };
});

该指令是我的一个应用程序的一部分,并且它仍然是应用程序的一部分很重要。但是,我也想在其他项目中使用相同的指令,目前我正在使用 Bower 将存储库拉到我的其他项目中。但是,该指令将会中断,因为 templateUrl 不正确。Bower 克隆了我的整个项目,而模板的实际路径充其量在我的其他项目中需要是这样的:

/lib/public/foo/bar.html

其他人如何处理这个问题?

有帮助吗?

解决方案

由于可维护性问题,我从来不喜欢使用模板字符串进行模板化。我很快就制作了 html 原型,所以我选择了一个 grunt 任务来读取我的文件并将它们处理成一个单一的文件 $templateCache js 文件。

解决方案

Grunt 角度模板

在$ templatecache中grunt构建任务以连接并注册您的angularjs模板

// within my Gruntfile.js
grunt.initConfig({
  ngtemplates: {
    'angular-my-directives': {
      src:      'views/**/*.html', // where my view files are
      dest:     'src/templates.js' // single file of $templateCache
    }
  }
  // ...
});

生成类似以下内容: ./src/templates.js 它保留了我的文件夹结构:

angular.module('angular-my-directives').run(['$templateCache', function($templateCache) {

  $templateCache.put('views/directives/my-download.html',
    "<form name=\"myDownloadForm\" ng-submit=\"submit()\" novalidate>\n" +
    "</form>"
  );

}]);

现在在我的指令中我可以简单地使用 templateUrl: 'views/directives/my-download.html' 它将使用 $templateCache。

最后我用了 grunt-contrib-concat 合并我的文件以便于加载。

查看 ”使用源映射进行 Grunt concat + uglify”(或在评论中留下更好的链接)以了解如何将 js 文件合并 + uglify(又名 min)到单个“dist”文件中。

如果正在开发您自己的定制凉亭包..

请务必将串联(也称为构建)文件提交到包存储库,以便您的包使用者可以简单地包含 my-concat-package.js 或者 my-concat-package.min.js

其他提示

角指令具有生成扫描码和templateUrl属性。template接收HTML字符串。这不是一个完美的解决方案,因为您需要将HTML放入您的JS中。但它是库创建者的常见模式,将HTML字符串直接放在template属性上,因此它们可以将其模块包装成一个文件。

您可能希望将该TemplateUrl-to模板制作您lib的构建步骤。

看看角引导bower repo

一个解决方案,以及我个人的首选解决方案,是将模板放入世代odicetagcode函数中的$templateCache。这样你永远不必担心引用错误的问题 - 你可以给它任何任意识别你想要的网址 - 它永远不会需要一个HTTP请求来获取该模板,以引导。

在您的指令项目中:

使用xyz.tpl.html文件名创建所有模板,并使用所有JS代码放入指令指示。所有templateull看起来像

templateURL:'/template/my.tpl.html'

在App项目中:

在项目项目中创建Gulp / grunt任务,以将所有* .tpl.html文件复制到bower_components(默认)中的/模板/ dir中。

e.g。:

// copy template files
gulp.task('copy-tpl', function() {
    return gulp.src([
        config.dirs.src.bower_components + '/**/*.tpl.html'
    ])
            .pipe(flatten())
            .pipe(gulp.dest(config.dirs.build.tpl));
});
.

重要! /模板dir是一个惯例(作为js,css等)。

我已经给出了一个答案使用grunt将您的HTML文件构建到$ TEMPLATECACHE文件中,但自切换以来到Gulp,所以任何人都希望遵循相同的过程,但使用Gulp,checkout gulp-angular-templatecache

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top