0

I am fixing some small issues within our AngularJS application - I've come across the logic below which simply displays one link.

In pseudocode style..

if (data.serviceId exists in the DOM) {
    display link & populate the href from data.serviceId value
} elseif(commentReply.sender.serviceId exists in the DOM) {
    display the link & populate the href from commentReply.sender.serviceId value
}

The code itself in the template looks as follows, how can I amend the code below so it is cleaner and I am not duplicating the line using some form of single line tertiary statement?

<a ng-if="data.serviceId" ng-href="/#/profile/{{data.serviceId}}">View</a>
<a ng-if="commentReply.sender.serviceId" ng-href="/#/profile/{{commentReply.sender.serviceId}}">View</a>
Claies
  • 22,124
  • 4
  • 53
  • 77
Zabs
  • 13,852
  • 45
  • 173
  • 297

2 Answers2

1

Display one link and get your href value from the controller:

<a ng-href="/#/profile/{{ myCtrl.getServiceIdHref() }}">View</a>

Then add a function to your controller (following your pseudocode):

// inside myCtrl.js

this.getServiceIdHref = function() {
    if (data.serviceId exists in the DOM) {
        return data.serviceId value
    } elseif(commentReply.sender.serviceId exists in the DOM) {
        return commentReply.sender.serviceId value
    }
}
Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
  • thanks @Omri this is the better method of the two in all honesty but I just needed something 'quick' so went with the other answer but this answer is good to illustrate the 'best' way to do this – Zabs Sep 07 '16 at 14:42
1

for example:

<a data-ng-href="/#/profile/{{data.serviceId && !commentReply.sender.serviceId ? data.serviceId : commentReply.sender.serviceId}}">View</a>

or

<a href="/#/profile/{{data.serviceId && !commentReply.sender.serviceId ? data.serviceId : commentReply.sender.serviceId}}">View</a>
Zabs
  • 13,852
  • 45
  • 173
  • 297
Koudi
  • 92
  • 3