Zelter Ady
Zelter Ady

Reputation: 6338

angular link or span

Beginner question: I need to create an html element that depends on a controller variable. I get some data as JSON on controller and now I want to create the view. On json I can have

{
    "text": "England",
}

or

{
   "text": "England",
   "url": "http://england.com/"
}

Here comes the question: I want to create a span if no url provided, else a link (a). Is possible to do this without creating both elements and using ng-show or ng-hide?

Upvotes: 2

Views: 2501

Answers (1)

Blake
Blake

Reputation: 641

There are a few different ways you could handle it. Show hide would work, you could also use ng-if like so:

<span ng-if="url == null"></span>
<a ng-if="url != null" href="url"></a>

ng-if won't render the object in the DOM if it fails, unlike hide/show which will have the object in the DOM but use styles to show and hide it.

You could also just have a span that has an ng-click on it. The click could just return nothing if there is no url.

 <span ng-click="myFunction(url)"></span>
$scope.myFunction = function(url){
  if(!url){
    return null;
  } else{
    window.location.href = url;
  } 
}

Upvotes: 4

Related Questions