1

Is that possible to insert HTML elements in an Angular expression ? Let's take a few example.

I would like to do something like this:

<table>
    <tr ng-repeat="employee in employees">
        <td>{{employee.firstname ? employee.firstname : '<p style="color:red">No name</p>'}}</td>
        <td>{{employee.job}}</td>
    </tr>
</table>

In our controller, we have:

$scope.employees = [{firstname:'Bob', job:'Developer'},
                    {firstname:'Paul', job:'Manager'},
                    {job:'Developer'}]

We show all employees (name/job), when we don't have the name of the person, we show No name.

Thanks :)

3 Answers 3

2

You could use ng-show, it will show the paragraph if employee.firstname is null.

<tr ng-repeat="employee in employees">
    <td>{{employee.firstname }}<p ng-show="!employee.firstname" style="color:red">No name</p></td>
    <td>{{employee.job}}</td>
</tr> 
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply use ng-if in this case

<tr ng-repeat="employee in employees">
    <td ng-if="employee.firstname">{{employee.firstname}}</td>
    <td ng-if="!employee.firstname"><p style="color:red">No name</p></td>
    <td>{{employee.job}}</td>
</tr>

2 Comments

Maybe this could be better ? <tr ng-repeat="employee in employees"> <td ng-if="employee.firstname">{{employee.firstname}} <p style="color:red" ng-if="!employee.firstname">No name</p> </td> <td>{{employee.job}}</td> </tr>
@Mistalis: IMHO ng-if in this scenario is more apt as you need to check the condition only once. So if firstname is not there then DOM elements wont increase
0

You can use ng-bind in this case

<tr ng-repeat="employee in employees" ng-bind="functionName(argument);"></tr>

And in the controller, you can put your logic inside the functionName() function.

$scope.functionName(){
  //Your logic goes here
}

Based on your condition, return the relevant html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.