mrtriangle
mrtriangle

Reputation: 544

Conditionally Alter link in button in Angular

I am trying to figure out a simple way to swap a link in a button in angular js, I have properties available in the scope that I can use, but I am not sure how to implement. The link I am trying to alter is in the 'onClick' attribute in the button. Thanks again in advance, here is my code:

<div class="instructions-button">
      <button
      type="button"
      class="halo-modal-action-button external-instructions"
      onClick="window.open('https://mysite/foo');"
      window="new"
      ng-disabled=""
      ng-click=""
      data-bs-enabled=""
      >Instructions</button>
    </div>

I am trying to make a simple conditional to show either:

'mysite/foo || mysite/bar' 

but am not sure how to make it work.

Upvotes: 0

Views: 417

Answers (3)

Tristan
Tristan

Reputation: 3321

Two simple ways to do this.

1) Two buttons and show one conditionally with ng-show.

<button ... ng-show="conditionShowFooTrue" >
<button ... ng-show="conditionShowBarTrue" >

2) Use ng-click to call a scope function to conditionally sets the url as the other answers have suggested.

Upvotes: 2

groooves
groooves

Reputation: 470

If you're using routes, you can just use ng-click like @Akxe said, and with the $location service in your controller, do:

$scope.changeLocation = function(){
  if(condition)
  {
    $location.path('/foo');
  } else
  {
    $location.path('/bar');
  }
};

I think that would be the Angular way to do this.

Upvotes: 1

Akxe
Akxe

Reputation: 11495

Don't use onClick event on the button, although it might feel weird to you, since you are coming from vanilla JS, you should use ng-click.

<button
      class="halo-modal-action-button external-instructions"
      ng-disabled=""
      ng-click="openWindow()"
      data-bs-enabled=""
      >Instructions</button>

and inside controller

$scope.openWindow = function(){
    if ( condition ) {
        open('http:foo.bar')
    } else {
        open('http:bar.foo')
    }
}

Upvotes: 5

Related Questions