Reputation: 1391
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?
Upvotes: 0
Views: 1061
Reputation: 2750
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!");
};
Upvotes: 1
Reputation: 338
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 = '');
})
Upvotes: 0