javascript AngularJS - 通过指令向按钮添加 onClick 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25910522/
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-28 05:12:35  来源:igfitidea点击:

AngularJS - Adding an onClick event to a Button via a Directive

javascriptangularjs

提问by olu

I'd like to add a click event to an element with a directive. The important part is to not define the button or hyperlink or whatever in the directive but only the onClick attribute and the function, that is called.

我想向带有指令的元素添加点击事件。重要的部分是不要在指令中定义按钮或超链接或其他任何东西,而只定义 onClick 属性和调用的函数。

So the HTML looks something like this:

所以 HTML 看起来像这样:

<button my-dir type="button" class="btn btn-primary">test</button>

My directive looks like this:

我的指令如下所示:

.directive('myDir', function(){
   return {
       restrict: 'A',
       scope: true,
       link: function(scope, element, attrs) {

           scope.functionToBeCalled = function(){
               console.log("It worked!");
           }
       }
   }
})

I have tried adding a "click" like this:

我曾尝试添加这样的“点击”:

element.bind('click',scope.functionToBeCalled());

Unfortunately this calls the function once when link is called, but not when the button is clicked. I think I have to use compile rather than link and move the functionToBeCalled into the function returned by compile. Sadly I don't know how to accomplish that.

不幸的是,这会在调用链接时调用该函数一次,但在单击按钮时不会调用该函数。我想我必须使用编译而不是链接并将 functionToBeCalled 移动到编译返回的函数中。可悲的是,我不知道如何做到这一点。

Thanks for your help!

谢谢你的帮助!

回答by dfsq

It should be like this:

应该是这样的:

.directive('myDir', function () {
    return {
        restrict: 'A',
        scope: true,
        link: function (scope, element, attrs) {

            function functionToBeCalled () {
                console.log("It worked!");
            }

            element.on('click', functionToBeCalled);
        }
    };
});

The line of yours element.bind('click', scope.functionToBeCalled())is not correct, because you want to pass function reference, not the result of its immediate invocation (what happens if you put ()after function name).

你的那行element.bind('click', scope.functionToBeCalled())是不正确的,因为你想传递函数引用,而不是它立即调用的结果(如果你把()函数名放在后面会发生什么)。