Angular - 指令和使用模块

luc*_*uma 5 javascript angularjs angularjs-directive

在研究了各种不同的项目并阅读尽可能多的文档后,我遇到了如何在我的应用程序中包含指令的问题.该应用程序的设置如下:

app.js - 只是顶部

angular.module('ngDashboard', ['ngCookies','ngResource','ngDashboard.filters', 'ngDashboard.services', 'ngDashboard.directives'])
Run Code Online (Sandbox Code Playgroud)

除了(它是一个从一个例子重写的应用程序)之外,所有模块都能正常工作,因为这些指令根本不起作用:

directives.js - 以下不起作用,不在视图上执行指令:

angular.module('ngDashboard.directives', []).
  directive('funkyElement', function () {
    return {
        restrict: 'E',
        transclude: true,
        scope: 'isolate',
        template: '<div>gonna parse this: {{orig}} <br/>... and get this: {{obj}}</div>',
        //templateUrl: 'template.html',
        compile:function (element, attr, transclusionFunc) {
            return function (scope, iterStartElement, attr) {
                var origElem = transclusionFunc(scope);
                var content = origElem.text();
                scope.orig = content;
                scope.obj = my_custom_parsing(content);
            };
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

同一个directives.js文件中的以下内容可以正常工作并执行指令:

angular.module('ng').directive('funkyElement', function () {
    return {
        restrict: 'E',
        transclude: true,
        scope: 'isolate',
        template: '<div>gonna parse this: {{orig}} <br/>... and get this: {{obj}}</div>',
        //templateUrl: 'template.html',
        compile:function (element, attr, transclusionFunc) {
            return function (scope, iterStartElement, attr) {
                var origElem = transclusionFunc(scope);
                var content = origElem.text();
                scope.orig = content;
                scope.obj = my_custom_parsing(content);
            };
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

HTML很简单:

<funky-element>
    Parse me... come ooooon! Just parse meee!
</funky-element>
Run Code Online (Sandbox Code Playgroud)

我的问题是,包含一组指令的正确方法是什么,也许为什么第一个例子(使用ngDashboard.services)不起作用.

luc*_*uma 5

事实证明,我所拥有的app.js文件要么被缓存所以指令依赖不存在,要么我忽略了保存它(两者都可能是周末工作和深夜工作).由于此问题在我对app.js进行更新后得到修复,因此我会将此标记为已解决,并提供以下建议:

  1. 检查脚本控制台以确保不缓存文件
  2. 完全关闭缓存,或使用隐身模式.
  3. 始终确保ng-app已添加到您的文档中(不是这样,但可以帮助其他人)
  4. 确保保存文件
  5. 疲倦时喝更多咖啡,学习新的编程语言/框架.

最后关于Angular,我没有意识到你可以向ng模块添加指令,它们就可以使用了.我确信这不是最佳实践,但是为了测试和组合快速代码,它可能会派上用场.