javascript AngularJS 指令链接功能不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11622135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:50:42  来源:igfitidea点击:

AngularJS directive link function not working

javascriptangularjs

提问by CoderMD666

http://jsfiddle.net/kz26/kH9wg/

http://jsfiddle.net/kz26/kH9wg/

I'm playing around with directives in AngularJS and have trying both the shorthand directive style (returning only the link function) and the longhand style (returning all or part of a directive definition object.

我正在使用 AngularJS 中的指令,并尝试了速记指令样式(仅返回链接函数)和普通样式(返回指令定义对象的全部或部分)。

Unfortunately, I've only been able to get the directive working (which activates a jQuery popup) using the shorthand way defined in popup2. The longhand popup2directive doesn't seem to work at all, and in particular the linkfunction in my definition object is never called. What do I need to do to make this explicit link declaration to work?

不幸的是,我只能使用popup2. 普通popup2指令似乎根本不起作用,特别是link我的定义对象中的函数从未被调用。我需要做什么才能使这个显式链接声明起作用?

回答by Gloopy

Both of your directives work with a small tweak to reuse the same module when creating the directives instead of overwriting the first one. See this fiddle.

您的两个指令都进行了小调整,以在创建指令时重用相同的模块,而不是覆盖第一个。看到这个小提琴

Instead of doing:

而不是做:

angular.module("app", []).directive('popover1'...

angular.module("app", []).directive('popover2'...

Do something like this:

做这样的事情:

var module = angular.module("app", []);

module.directive('popover1'...

module.directive('popover2'...

Edit:after looking at the docsI see you can do something similar to the original post as well like this:

编辑:在查看文档后,我发现您可以执行类似于原始帖子的操作,如下所示:

angular.module('app', []).directive('popover1'...

angular.module('app').directive('popover2'...

Omit the second parameter []in subsequent calls after the first to angular.moduleto configure an existing module.

[]在第一个 to 之后的后续调用中省略第二个参数angular.module以配置现有模块。

回答by Luckylooke

And why the link function isnt called here?:

为什么这里没有调用链接函数?:

<div ng:app="app">
<div>
    <p test="">Hello!</p>
</div>

var module = angular.module("app", []);

module.directive('test', function() {
return {
        restrict: '',
        link: function () {
            console.log('linkfn');
        },
        compile: function() {
            console.log('compile');
        }
    };

});

fiddle: http://jsfiddle.net/ZWLzb/

小提琴:http: //jsfiddle.net/ZWLzb/