Search code examples
javascriptangularjsangularjs-ng-repeatconditional-operatorangular-ng-if

Angular js (1.4) Using Ternary operator inside ng-repeat to show different html?


<tr ng-repeat="(field, value) in vm.params track by $index">
  <td>{{::field}}</td>
  <td  hkey="{{field}}">  {{value.include('http')?<a href ="{{value}}">{{value}}</a>:{{value}} }}</td>

</tr>

In the above Angular view I wanted the value field to check if the value contains string 'http', if so wrap an anchor tag around it so its clickable else show regular text value.

Its not working out right , here its what its showing,

enter image description here

how to do this properly?.

i attempted to do it from the controller like this

      vm.params["Source Link"]?vm.params["Source Link"] = '<a href='+vm.params['Source Link']+'>link</a>':""

But data is displaying in string form not html, i see it with anchor tag and everything.

vm.params looks something like this

    {
    Provider Name: "MARIO BLOUNT",
    Provider State: "WV",
    Provider City: "BRIDGEPORT",
    Action Date: "06/03/2014",
    Provider Source: "HEALTH CARE FRAUD FILE",
    Provider Type: "PHARMACIST",
    Action Description: "CHARGED BY INDICTMENT WITH CONSPIRACY TO ILLEGALLY 
    PRESCRIBE AND DISTRIBUTE OXYCODONE",
    Clinic Name: "BEST CARE PHARMACY; MARIO DAVID BLOUNT RPH",
    Source Link: "https://www.dea.gov/press-releases/201",
    }


Solution

  • the ternary operator isn't gona work for template like this, it'll have to look like this...

    <td ng-if="value.includes('http')" hkey="{{field}}"> <a href ="{{value}}">{{value}}</a></td>
    <td ng-if="!value.includes('http')" hkey="{{field}}">{{value}}</td>
    

    but be careful as this is not great for change detection since you'll run that includes check 2xN params on every change detection cycle.

    if you can reliably do like:

    ng-if="field === 'Source Link'"
    

    instead, that would perform better, or you're at least better off using value.startsWith('http')