Manuel Di Iorio
Manuel Di Iorio

Reputation: 3761

Prevent nested ui-sref to be triggered when there is a parent ng-click

Pratically the inverse of Prevent calling parent when nested ui-sref

I want to click on a nested element which has a ui-sref, but instead only the parent ng-click should be triggered (conditionally), stopping the propagation to the nested children elements.

That's my code:

// 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;
}

Right now with this code, when I click on the nested element, both parent ng-click and ui-sref are triggered. Only the parent should be called.

Reason is that I want to avoid the duplication of code with two ng-if with multiple elements just for a click, but if you have another good way to do this, don't hesitate to comment! :)

Upvotes: 0

Views: 288

Answers (1)

erdysson
erdysson

Reputation: 1480

instead of ui-sref, you can use $state.go inside the controller :

// 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");
   }
};

Upvotes: 1

Related Questions