Is there a way to make an anchor tag trigger a function only if a specific variable is set? In this scenario, the variable name
is assigned the value of "Shnick"
, so when the link is clicked it should activate the func()
method. However, clicking the link does not produce any results.
If the name
variable is not set, I do not want the click
attribute to be visible, meaning the func()
method will not run.
I have attempted to find solutions by referring to these two answers on incorporating conditional attributes in Angular:
How to add conditional attribute in Angular 2?
What is the best way to conditionally apply attributes in AngularJS?
Unfortunately, none of those methods have yielded positive results for me. Below are my attempts at implementing the suggested solutions:
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 include the click
attribute so that it is added only when the name
variable is set and triggers the func()
method upon being clicked?