【问题标题】:AngularJS Linky filter stoppropagationAngularJS Linky过滤器停止传播
【发布时间】:2012-09-03 11:47:07
【问题描述】:

我有一个如下所示的span 标签:

<span ng-bind-html="item.Name | linky" ng-click="open(item)"></span>

在 ng-repeat 内。

我有一个问题,如果item.Name 包含电子邮件或链接,则链接过滤器会更改 html 并插入锚标记。现在,当我单击链接时,ng-click 触发并且锚点打开,但我只希望锚点打开并防止调用 ng-click ...这可能吗?

【问题讨论】:

  • 嗨!你知道这些点击回调是按什么顺序调用的吗?跨度之前的锚点?

标签: javascript onclick angularjs stoppropagation


【解决方案1】:

为你的 html 做这样的事情怎么样:

<span ng-bind-html="item.Name | linky" ng-click="open(item, $event)"></span>

这是你的函数调用:

$scope.open = function(item, event){
    if(event.srcElement.tagName !== 'A'){
        alert('do something here with ' + item.Name);
    }        
}

可能有更好的方法,但我相信这会奏效。虽然在documentation 里我看到$eventthis group article 里。

【讨论】:

  • 感谢您这样做!
【解决方案2】:

使用指令怎么样!

app = angular.module("myModule", ["ngSanitize"])
    .directive('linkyDir', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: { item: '=' },
            template: '<span ng-bind-html="item.Name | linky", ng-click="open(item)"></span>',
            controller: function($scope, $element) {
                $scope.open = function(item) {
                    if ($element[0].firstChild.tagName !== "A") {
                        console.log("Not an anchor");
                    } 
                    else {
                        console.log("Is an anchor tag");
                    }
                }
            }
        };
    })

加上限制:'E',你会这样称呼它

<p ng-repeat="item in items">
    <linky-dir item="item"></linky-dir>
</p>

【讨论】:

    【解决方案3】:

    我不知道这是否可行,但请尝试一下。

    在你的 open 函数中添加一个参数,并将 this 作为当前 dom 元素的指针传递。

    <span ng-bind-html="item.Name | linky" ng-click="open(item,this)"></span>
    

    现在在您的打开函数中 编辑代码:

     function open(item,this)
        {
          // will be true if linky had changed the HTML and added anchor tag
        var children = this.childNodes;   
        for(a in children ) 
        {
          if(children[a].href)
          {
              return false; 
          } 
        }   
     //your existing code
        .
        .
        .
    
        }
    

    所以该方法将被调用,但如果它是锚标记将返回 false。

    这可能不是你想要的,但它会达到你的目的:)

    【讨论】:

    • 似乎不起作用。 this 总是跨度,所以永远不会有 href 属性
    • 但你说linky改变了html并放置了anchore标签
    • 是的,锚标签在跨度内。这就是 ng-bind-html 的工作原理。它将值放在跨度内,并且 linky 重构 HTML 以包含锚点。最终的 html 看起来像 &lt;span&gt;&lt;a&gt;&lt;/a&gt;&lt;/span&gt;,因此将 this 放在 span 上将永远不会通过锚点到达 javascript。
    • 好吧,对 angularJs 不太了解,谢谢您的解释。我已经编辑了我的函数,试一试:)
    猜你喜欢
    • 2015-03-21
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    相关资源
    最近更新 更多