簡體   English   中英

AngularJS指令多個選擇器

[英]AngularJS directive multiple selectors

我想使我的指令多個選擇器。

我的指示是提醒每個輕拍。

我已經寫了這段代碼:

angular
    .module('app.directives')
    .directive('onTap', someDirective)
    .directive('button', someDirective);

someDirective.$inject = ['$ionicGesture'];

function someDirective($ionicGesture) {
    return {
        restrict: 'EA',
        link: link
    };

    function link($scope, $elem, $attrs) {
        $ionicGesture.on('tap', function() {
            alert('Tapped!');
        }, $elem);
    }
}

此代碼問題是此按鈕的示例:

<button on-tap="doSomething()">Do something</button>

因為點擊此按鈕將發出兩次警報!

我什至可以解決是否更改指令:

.directive('someDirective', someDirective);

但這意味着我必須將其添加到每個button[onTap]選擇器中。

有什么好的解決辦法嗎?

您可以嘗試以下方法:

function someDirective($ionicGesture) {
    var directive = {
        restrict: 'EA',
        link: link
    };

    return directive;

    function link($scope, $elem, $attrs, ctrls) {
        if (directive.name === 'onTap' && $elem.is('button')) {
            return;
        }

        $ionicGesture.on('tap', function() {
            alert('Tapped!');
        }, $elem);
    }
}

暫無
暫無

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

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