簡體   English   中英

向AngularJS轉換內容添加事件處理程序

[英]Add event handlers to AngularJS transclusion content

將事件處理程序添加到翻譯內容的正確方法是什么? 我不希望我的指令的使用者將他們自己的點擊處理程序添加到文檔中。 該指令應該處理它。 但我不確定如何正確地將處理程序添加到使用ng-transclude傳遞的內容中。

擺弄: https //jsfiddle.net/hoe71p0e/12/(無法使Angular.js和JSFiddle工作;我的鏈接函數未被調用)

foo.html

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

foo.js

return {
    template: "<div class='my-foo' data-ng-transclude></div>"
    link: function($scope, $elem, $attrs, $ctrl, $transclude) {
        $scope.foo = function() {
            console.log("this is never called");
        };

        $transclude(function(clone) {
            for (var i in clone) {
                if (clone[i].localName === "button") {
                    angular.element(clone[i]).attr("data-ng-click", "foo()");
                }
            }
        });
    }
};

預期結果 (點擊按鈕應調用foo)

<div class="my-foo">
    <button type="button" data-ng-click="foo()">Foo</button>
</div>

實際結果 (點擊按鈕什么都不做)

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

請注意,該按鈕上的data-ng-click屬性丟失。

另外,我看過幾個像這樣的例子......

broken.js

$transclude(function(clone) {
    angular.element(clone).find("button");
});

...但是那些失敗是因為.find()沒有返回結果,即使檢查員似乎認為克隆包含“按鈕”。

我無法想象你甚至連接這個指令。 在你的小提琴中,你缺少一些基本要求,例如ng-app="" ,在元素樣式指令中restrict: 'E' (1.2.x所需),並且transclude: true 通過這些修復,我們得到了一個有效的例子。 此外,我不確定你要用$transclude(function(clone) { /*...*/做什么$transclude(function(clone) { /*...*/ ,但我懷疑這是不必要的。請注意以下內容......

<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!');
            };
        }
    };
});

JSFiddle Link - 工作演示


根據會話,您可以采取的最直接的方法是利用$ compile服務並修改指令link <button> (一旦選中)元素的屬性。 注入$compile並觀察以下內容......

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

JSFiddle Link - $compile demo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM