oikonomiyaki
oikonomiyaki

Reputation: 7951

Evaluating expression inside angular directive

I want my table to conditionally render its row based on whether the value is null or not. The rows have different custom entries and labels, that's why I can't just use ng-repeat. Here's the code:

<table>
    <thead>
    </thead>
    <tbody>
        <tr ng-show = "{{data.entry_1}} !== null">
            <td>Custom Label 1</td>
            <td>{{data.entry_1}}</td>
        </tr>
        <tr ng-show = "{{data.entry_2}} !== null">
            <td>Custom Label 2</td>
            <td>{{data.entry_2}}</td>
        </tr>
        .
        .
        .
        <tr ng-show = "{{data.entry_n}} !== null">
            <td>Custom Label n</td>
            <td>{{data.entry_n}}</td>
        </tr>
    </tbody>
</table>

However, it seems that this way is not right. It's either javascript (compiler) is complaining at {{}} in the ng-show or at '!== null' or maybe both. How to evaluate an angular expression (in {{}}) inside an ng- directive?

I know that I could also evaluate this instead in the js file, but since I don't want to add further scope variables (to make my code cleaner), I chose to evaluate if it is null in the ng-show directive. Could someone tell me how to do it?

Thanks.

Upvotes: 0

Views: 501

Answers (2)

Martin
Martin

Reputation: 16300

You were close. The curly braces are only needed to echo/print/render the value of the variable. In an expression you should never use the curly braces.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app ng-init="data = {entry_1: 'notnull', entry_2: null, entry_n: 'againNotNull'}">
    <thead>
    </thead>
    <tbody>
        <tr ng-show="data.entry_1">
            <td>Custom Label 1</td>
            <td>{{data.entry_1}}</td>
        </tr>
        <tr ng-show="data.entry_2">
            <td>Custom Label 2</td>
            <td>{{data.entry_2}}</td>
        </tr>
        .
        .
        .
        <tr ng-show="data.entry_n">
            <td>Custom Label n</td>
            <td>{{data.entry_n}}</td>
        </tr>
        <tr ng-show="data.device">
            <td>Custom Device</td>
            <td>{{data.device}}</td>
        </tr>
    </tbody>
</table>

Upvotes: 1

skewl84
skewl84

Reputation: 184

Use $compile service in the context of the scope inside your directive.

See https://docs.angularjs.org/api/ng/service/$compile

Edit: I agree with Martin's answer.

Upvotes: -2

Related Questions