Jeff Finn Jeff Finn - 1 year ago 82
AngularJS Question

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">
<th>Result Value</th>
<th>Statement / Instructions</th>
<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 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">

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

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">

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

Answer Source

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">


    <td ng-if="::c.Statement">{{c.Statement}}</td>
    <td ng-if="::!c.Statement">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download