Javascript 向AngularJS转换内容添加事件处理程序

Javascript 向AngularJS转换内容添加事件处理程序,javascript,html,angularjs,angularjs-directive,angularjs-ng-transclude,Javascript,Html,Angularjs,Angularjs Directive,Angularjs Ng Transclude,向转换内容添加事件处理程序的正确方法是什么?我不希望我的指令的使用者将他们自己的点击处理程序添加到文档中。指令应该处理它。但我不确定如何正确地将处理程序添加到使用ng transclude传递的内容中 摆弄:(无法使Angular.js和JSFiddle工作;没有调用我的链接函数) foo.html <my-foo> <button type="button">Foo</button> </my-foo> …但是这些都失败了,因为.fin

向转换内容添加事件处理程序的正确方法是什么?我不希望我的指令的使用者将他们自己的点击处理程序添加到文档中。指令应该处理它。但我不确定如何正确地将处理程序添加到使用ng transclude传递的内容中

摆弄:(无法使Angular.js和JSFiddle工作;没有调用我的链接函数)

foo.html

<my-foo>
    <button type="button">Foo</button>
</my-foo>

…但是这些都失败了,因为
.find()
没有返回结果,尽管检查器似乎认为克隆包含一个“按钮”。

我无法想象您甚至在这个指令中链接。在fiddle中,您缺少一些基本要求,例如元素样式指令中的
ng app=”“
restrict:'e'
(1.2.x所需)和
transclude:true
。通过对这些问题的修正,我们得到了一个有效的例子。此外,我不确定您想用
$transclude(函数(克隆){/*…*/
做什么,但我怀疑这是不必要的。 注意以下几点

<my-foo>
    <button type="button" ng-click="foo()">Foo</button>
</my-foo>
.directive('myFoo', function($compile) {
    return {
        transclude: true,
        restrict: 'E',
        template: '<div class="my-foo" ng-transclude></div>',
        link: function($scope, elem, attrs) {

            $scope.foo = function() {
                console.log('called')
            }

            var button = elem.find('button');
            button.attr('ng-click', 'foo()');
            $compile(button)($scope);
        }
    };
});

-
$compile
demo

您在这里试图实现的目标并不明显。您试图实现的实际目标是什么?我不确定我是否遇到过指令以这种方式增加其他内容的原因。我想OP只是想在一个transcluded directi中调用他的
ng click
事件我已经添加了一个注释,解释我不希望指令的使用者被要求编写一个点击处理程序来使指令工作。基本上,我的指令应该有一个必需的“按钮”子项,但指令需要处理按钮的点击行为;使用者不应该是r负责。我向您保证,在我使用的实际代码中,正在调用link函数。关键是我的指令的使用者不应该添加他们自己的点击处理程序。这就是为什么我使用$transclude(显然是错误的…)好的,我想我明白你在做什么了。应该有一些方法。检查一下,让我知道这是否是你所倾向的方向?@richremand我们可以通过
$compile
或者甚至是一个可能的方法来做。仍然使用
$compile
,但只是将属性添加到元素中,而不是交换标记。我会说这是@richremeries!这正是我想要的最好的替代方法。如果你想用这些小提琴中的任何一个来更新答案,我会接受的。
<div class="my-foo">
    <button type="button">Foo</button>
</div>
$transclude(function(clone) {
    angular.element(clone).find("button");
});
<my-foo>
    <button type="button" ng-click="foo()">Foo</button>
</my-foo>
.directive('myFoo', function() {
    return {
        transclude: true,
        restrict: 'E',
        template: '<div class="my-foo" ng-transclude></div>',
        link: function($scope, elem, attrs) {
            $scope.foo = function() {
                console.log('this is called!');
            };
        }
    };
});
.directive('myFoo', function($compile) {
    return {
        transclude: true,
        restrict: 'E',
        template: '<div class="my-foo" ng-transclude></div>',
        link: function($scope, elem, attrs) {

            $scope.foo = function() {
                console.log('called')
            }

            var button = elem.find('button');
            button.attr('ng-click', 'foo()');
            $compile(button)($scope);
        }
    };
});