如何在不发送HTML代码的情况下共享AngularJS指令

How to share AngularJS directives without the need to send HTML code

本文关键字:情况下 共享 AngularJS 指令 代码 HTML      更新时间:2023-09-26

我正在创建一个AngularJS模块,其中包含一些将在我的组织内的其他项目中重用的指令。目前,当一些项目需要使用这个泛型模块时,我需要发送两件事:javascript和所有创建指令的AngularJS代码,以及我的指令使用的所有模板视图

我当前的结构如下:

var commonWidgets = angular.module('commonWidgets', []);
commonWidgets.directive('commonGrid', function () {
    return {
        restrict: 'A',
        scope: {
            options: '='
        },
        templateUrl: '/views/grid.html',
        link: function (scope) {
           ...
        }
    };
});

在这个例子中,我必须与其他项目共享common-widgets.js和/views/grid.html。

问题:是否有一种方法,我可以只发送javascript代码?

我认为一个可能的解决方案是像下面这样声明我的javascript代码:
var commonWidgets = angular.module('commonWidgets', []);
commonWidgets.directive('commonGrid', function () {
    return {
        restrict: 'A',
        scope: {
            options: '='
        },
        template: '<div>A relative big code goes here</div>',
        link: function (scope) {
           ...
        }
    };
});

问题是,当我在Javascript代码中有模板时,很难维护。另一方面,这个库的使用者不需要担心视图。

是否有一种方法,我可以改变templateUrl模板,而构建一个生产就绪的AngularJS库?

第一个选项

你可以使用$templateCache服务和

commonWidgets.run(function($templateCache) {
  $templateCache.put('/views/grid.html', 'This is the content of the template');
});

只要commonWidgets是模块的名称

第二选项

你可以使用grunt-angular-templates从已有的模板中生成$templateCache。

第一种和第二种可能的结合对你来说是最好的。

ngtemplates任务

我的Gruntfile的一部分,任务ngtemplates with在构建过程

中被调用
ngtemplates: {
      app: {
        cwd: 'app',
        src: 'views/**/*.html', // all subdirectories
        dest: '.tmp/templates.js',
        options: {
          htmlmin: '<%= htmlmin.dist.options %>',
          usemin: 'scripts/modules.js', // append .tmp/tempaltes to scripts/modules.js file
          module: appName // global appName from Gruntfile config section
        }
      }
    }

最好的方法是使用Grunt将HTML构建到单个JS文件中。

Grunt有一个插件grunt-angular-templates,它可以将你所有的HTML模板转换成一个JavaScript文件,并将它们注册到Angular中,这样你就不必更改任何代码。

然后,你可以简单地分发你生成的JS而不是你的HTML文件。