AngularJS - 如何模块化指令+模板组合?

bio*_*all 14 directive angularjs bower

这是情况.我有一个指令,取决于templateUrl.

该指令看起来像这样:

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

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

/lib/public/foo/bar.html

其他人如何管理这个?

ele*_*ake 10

由于可维护性问题,我从未喜欢使用模板字符串进行模板化.我非常快速地原型化html所以我选择了一个grunt任务,它读取我的文件并将它们处理成一个$ templateCache js文件.

Grunt Angular模板

Grunt构建任务以在$ templateCache中连接和注册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
    }
  }
  // ...
});
Run Code Online (Sandbox Code Playgroud)

生成类似于:./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>"
  );

}]);
Run Code Online (Sandbox Code Playgroud)

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

最后,我使用grunt-contrib-concat来组合我的文件以便于加载.

结帐" Grunt concat + uglify with sourcemaps "(或在评论中留下更好的链接)以了解如何将+ uglify(aka min)js文件连接到单个"dist"文件中.

如果你自己定制凉亭包..

确保将连接(也称为构建)文件提交到包repo,以便您的包消费者可以简单地包含my-concat-package.jsmy-concat-package.min.js


Ken*_*aka 5

角指令具有templateUrltemplate性能.template收到一个HTML字符串.它不是一个完美的解决方案,因为您需要将HTML放入JS中.但是,对于库创建者来说,将HTML字符串直接放在template属性上是一种常见的模式,因此他们可以将模块包装到单个文件中.

您可能希望将templateUrl-to-template作为lib的构建步骤.

看一下Angular Bootstrap Bower Repo.