【问题标题】:Prevent nested ui-sref to be triggered when there is a parent ng-click防止在有父 ng-click 时触发嵌套的 ui-sref
【发布时间】:2017-06-18 04:51:30
【问题描述】:

实际上是Prevent calling parent when nested ui-sref的倒数

我想单击具有 ui-sref 的嵌套元素,但应仅触发父 ng-click(有条件地),停止传播到嵌套子元素。

这是我的代码:

// Template:
<div ng-click="canClick && openAnotherLink($event)">
    <a ui-sref="myState">
        I wanna click here to trigger the parent ng-click. 
        Overriding the default ui-sref behavior
    </a>
</div>

// Controller:
$scope.canClick = true;

$scope.openAnotherLink = ($event) => {
    $event.stopPropagation(); // <-- this does not works
    // $event.preventDefault() // <-- I tried even this, not working
    window.open('http://google.com', '_blank');
    return;
}

现在使用这段代码,当我点击嵌套元素时,父级 ng-click 和 ui-sref 都会被触发。应该只调用父级。

原因是我想避免重复代码与两个 ng-if 与多个元素只是为了点击,但如果你有另一种好方法来做到这一点,不要犹豫评论! :)

【问题讨论】:

    标签: javascript angularjs angular-ui-router


    【解决方案1】:

    您可以在控制器内部使用 $state.go 来代替 ui-sref:

    // Template:
    <div ng-click="canClick && openAnotherLink()">
        <a ng-click="goToState($event)">
            I wanna click here to trigger the parent ng-click. 
            Overriding the default ui-sref behavior
        </a>
    </div>
    
    // Controller: I assume you injected the "$state" provider
    $scope.canClick = true;
    
    $scope.openAnotherLink = () => {
        window.open('http://google.com', '_blank');
    }
    
    $scope.goToState = function goToState(e) {
       if (!$scope.canClick) {
          e.stopPropagation();
          $state.go("myState");
       }
    };
    

    【讨论】:

      猜你喜欢
      • 2014-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      相关资源
      最近更新 更多