include html templates in a bower component for an

2019-07-21 08:51发布

I'm making some reusable directives for my angular apps by putting them in a separate bower component.

I would like to use a templateUrl for the directives so that I am not forced to do one of the three options in this post: How do I use separate templates with my angular directive bower package? Here is amoderate paraphrasing of the suggestions: 1 copy and past html in to the js file, 2 using grunt to compile the templates into js, or 3 put the templates in a different directory and have the server handle the requests, so that the directives are not usable by bower installation only.

Is there a better way to use template files for the directives in the component, or is bower just not set up to work in this manner?

1条回答
Root(大扎)
2楼-- · 2019-07-21 09:47

I did resolve this issue. I'm sorry for not posting the answer earlier.

I ended up using grunt-angular-templates

If you are using gulp, there is probably a comparable library.

This was my directory structure, with my html in the templates directory

project
 src
   controllers
   directives
   templates

And this is how I configured my the options for it in my Gruntfile

 grunt.initConfig({
 ...
 ngtemplates: {
   projectName: {
     cwd: 'src',
     src: 'templates/**/*.html',
     dest: 'src/templates/templates.js'
   }
 }

I have another grunt task grunt-contrib-concat to concat all the javascript files within the project. So, the templates get bundled into the final js file.

In the code and tests, you will be able to reference your html files the same way regardless of if you are loading the html or javascript version.

Ex:

angular.module('myModule')
  .directive('myModuleDirective', function () {
    return {
        restrict: 'E',
        templateUrl: 'templates/mainTemplate.html'
    };
});
查看更多
登录 后发表回答