0

I am trying to make an anchor tag trigger a function if a particular variable is set. In the example below name is set to "Shnick" and so the link when clicked should trigger the func() method. However, nothing happens when I click the link.

If the name is not set, then I do not want the click attribute to appear and so the func() method won't execute.

I have tried looking at these two answers on adding conditional attributes in Angular:

But none of those have worked. Here are my attempts at using the two answers presented above

Attempt #1:

angular.module('myApp', [])
  .controller('myController', function ($scope) {
    $scope.name = "Shnick";
    $scope.func = function() {
      alert("Link Clicked!");
    };
  });

angular.element(document).ready(function () {
  angular.bootstrap(document, ['myApp']);  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-controller="myController">
  <p>Name: {{ name }} </p>
  <a href="#" [attr.click]="name ? func() : null">Click me</a>
</div>

Attempt #2:

angular.module('myApp', [])
  .controller('myController', function ($scope) {
    $scope.name = "Shnick";
    $scope.func = function() {
      alert("Link Clicked!");
    };
  });

angular.element(document).ready(function () {
  angular.bootstrap(document, ['myApp']);  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-controller="myController">
  <p>Name: {{ name }} </p>
  <a href="#" ng-attr-click="name ? func() : undefined">Click me</a>
</div>

So, how can I conditionally add the click attribute such that it is only added when name is set and will execute the func() method when clicked?

Shnick
  • 1,199
  • 1
  • 13
  • 32
  • 2
    I'd recommend not changing the link, but put some logic in the function instead, and let that logic determine what to do. It's much easier and makes the markup tidier and easier to follow. – Reinstate Monica Cellio Jun 27 '19 at 07:37
  • I would recomend creating a new function of the form `function onAnchorClick(){if (this.name) this.func(); }` – nick zoum Jun 27 '19 at 07:40

2 Answers2

1

Try not to overcomplicate things with ternary conditions, add this checking logic inside the function itself, something like this should work:

$scope.func = function() {
  if(!$scope.name) {
    return;
  }
  alert("Link Clicked!");
};
JSEvgeny
  • 2,550
  • 1
  • 24
  • 38
0

HTML Code:

<a ng-href='{{link}}' ng-click='test(type);'> your link </a>

js code:

$scope.name = "";
$scope.$watch('m', function(value){
    ($scope.name = "Shnick") ? ($scope.link = 'actual_link') : ($scope.link = '');
})
Vinod Bokde
  • 338
  • 2
  • 14