require.js从其他模块使用AngularJS指令

时间:2018-08-31 23:55:21

标签: javascript angularjs requirejs

模块的指令在被另一个模块调用时不会被引导

我有一个AngularJS网络应用,其中包含一个名为“ heroEditor”的模块:

// 3) heroEditor ng module is created and injects the dataListPane
// module as a dependency (see step 1)
define('heroEditor/module',['common/module', 'dataListPane/module'], function(){
    return angular.module('heroEditor', ['common', 'dataListPane']);
});

如您在上面看到的,这取决于下面另一个名为'dataListPane'的ng模块:

// 1) define the dataListPane ng module
define('dataListPane/module',[], function(){
    return angular.module('dataListPane', []);
});

所有这些都通过requirejs连接起来,并且一切都以正确的顺序调用。在模块“ heroEditor”中,我有一条指令,也称为“ heroEditor”:

// 4) Register the heroEditor directive on the heroEditor module
// this directive will try to consume a dataListPane directive instance
// which should be available as it was registered (see step 2)
define('heroEditor/directive/heroEditor',['heroEditor/module', 'heroEditor/service/heroData'], function(heroEditorMod){
    heroEditorMod.directive('heroEditor', ['heroData', function(heroData){
        //hero editor directive definition
    });
});

在依赖项中,“ dataListPane”模块是我要在“ heroEditor”指令的标记内使用的指令。这是“ dataListPane”指令:

// 2) Register the dataListPane directive on the dataListPane module
define('dataListPane/directive/dataListPane',['dataListPane/module'], function(dataListPaneMod){
    dataListPaneMod.directive('dataListPane', function(){
        // [NEVER CALLED] data list pane directive content
        return {scope:{},templateUrl:'a/valid/path/to/dataListPane.html'};
    });
});

在英雄编辑器的标记中,我尝试像这样放置数据列表窗格指令的实例(它应该可用!)

<data-list-pane></data-list-pane>

在浏览器中,尽管我将其包含在标记中,但数据列表窗格的指令功能从未触发。从requirejs角度进行注入工作正常。当我创建英雄编辑器模块并将其赋予dataListPane模块依赖项时,Ng也不会引发异常(这意味着它知道该模块存在!)

我正在使用ng 1.7.2

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您尚未显示任何片段,这些片段指示您如何在较高级别(例如一些基本ConsumerAwareRebalanceListener文件)中将RequireJS模块组合在一起。但是,我怀疑您的app.js模块永远不会成为任何RequireJS依赖项定义的一部分(即从dataListPane/directive/dataListPane无法访问),这就是内部代码从不执行的原因。

确保引入AngularJS样式的模块的声明的一种方法是让AngularJS模块本身确保执行此类声明的代码。

app.js

I've made a working demonstration of this approach here.

关于上述方法的两点:

  1. 分隔的指令定义(在您的情况下为// dataListPane/module.js define( 'dataListPane/module', ['dataListPane/directive/dataListPane'], function (dataListPane) { var mod = angular.module('dataListPane', []); return function () { dataListPane.init(mod); return mod; }; }); // dataListPane/directive/dataListPane.js define( 'dataListPane/directive/dataListPane', // You cannot depend on 'dataListPane/module' here! (i.e. cyclic dependency) ['exports'], function (exports) { exports.init = function (mod) { // mod.directive(...) }; }); )不能显式依赖需要在其上声明的AngularJS模块,否则它是循环依赖项
  2. 请注意,AngularJS模块显式依赖于指令定义所在的RequireJS模块并对其进行初始化