AngularJS - 通过指令向按钮添加onClick事件 [英] AngularJS - Adding an onClick event to a Button via a Directive

查看:158
本文介绍了AngularJS - 通过指令向按钮添加onClick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将click事件添加到带有指令的元素中。重要的是不要在指令中定义按钮或超链接或其他内容,而只定义onClick属性和调用的函数。

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.

所以HTML看起来像这个:

So the HTML looks something like this:

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

我的指令如下所示:

.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());

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

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.

感谢您的帮助!

推荐答案

它应该是这样的:

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

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

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

你的行 element.bind('click',scope.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).

这篇关于AngularJS - 通过指令向按钮添加onClick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆