Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only use ng-if the first time the data loads

Hi I have a table that is populated using ng-repeat. Each row of the table has a few inputs that are saved to a database.

My API passes a View Model as JSON to Angular, if there is already a value for a object I want to display the value in the column without the input.

This is my table

<table class="table table-responsive">
<thead>
    <tr>
        <th></th>
        <th>Result Value</th>
        <th>Statement / Instructions</th>
    </tr>
</thead>
<tbody>
    <tr data-ng-repeat="c in myData.items">
        <td>{{ c.Name }}</td>

        <td ng-if="c.NumericValue">{{c.NumericValue}}</td>
        <td ng-if="!c.NumericValue">
            <input type="text" name="value" data-ng-model="c.NumericValue" data-ng-trim="false">
        </td>

        <td ng-if="c.Statement">{{c.Statement}}</td>
        <td ng-if="!c.Statement">
            <input type="text" name="statement" data-ng-model="c.Statement" data-ng-trim="false">
        </td>
    </tr>
</tbody>

This almost works except that when I enter in a single character into the input box the input is removed and the value is shown as text. I know that this is how Angular is supposed to work but is there a way of only checking the data when the data loads the first time and stop Angular reloading the cells contents so that I can enter in my data fully without reloading the cells contents.

I'm sorry if this is basic but I'm only starting to use Angular and I'm not fully familiar with everything it can do yet.

Thanks in advance for any help

UPDATE To try and clarify, ng-if checks if c.NumericValue is empty. If it is empty the input is displayed. When I enter in a value after I enter the first character of the value. The input box is removed and replaced with

<td ng-if="c.NumericValue">{{c.NumericValue}}</td>

What I want is that when the table is loaded to check if c.NumericValue has a value. IF it does show

<td ng-if="c.NumericValue">{{c.NumericValue}}</td>

otherwise let me input the value using

<td ng-if="!c.NumericValue">
    <input type="text" name="value" data-ng-model="c.NumericValue" data-ng-trim="false">
</td>

For example if I want to enter in '10' after I enter in '1' the input box is replace with the text '1'.

like image 226
Jeff Finn Avatar asked Jan 23 '26 18:01

Jeff Finn


1 Answers

If I understand your question, I think you will want to use one time binding (introduced in AngularJS 1.3) so that the ng-if won't keep being reevaluated after the first digest. Like this:

    <td ng-if="::c.NumericValue">{{c.NumericValue}}</td>
    <td ng-if="::!c.NumericValue">

and

    <td ng-if="::c.Statement">{{c.Statement}}</td>
    <td ng-if="::!c.Statement">
like image 173
jbrown Avatar answered Jan 26 '26 11:01

jbrown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!