Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ng-init if array not yet created

I'm trying to build a template for a application and want to display a dynamic list with names. so i got this code to show the list and add/remove rows;

<table ng-init="page.businessRows = []">
<thead>
    <tr>
        <th>Company</th>
        <th>Contact</th>
        <th>Phone</th>
    </tr>
</thead>
    <tr ng-repeat="row in page.businessRows">
        <td>
            <input type="text" ng-model="row.name" />
        </td>
        <td>
            <input type="text" ng-model="row.contact" />
        </td>
        <td>
            <input type="text" ng-model="row.phone" />
        </td>
        <td>
            <button ng-click="page.businessRows.splice($index,1)">
                Remove
            </button>
        </td>
    </tr>
</table>
<button class="btn" ng-click="page.businessRows.push({})">addRow</button>

the thing as that when this template is loaded page.busnessRows will most likely be loaded with rows so i want to change the ng-init to only create the empty array if businessRows is not initialised.

I have tried ng-init="page.businessRows = page.businessRows.length < 1 ? [] : page.businessRows but it did not work. How am i inteded to do conditions in jsangular expressions?

All help appreciated. Thanks in advance

like image 300
oBusk Avatar asked Aug 30 '13 16:08

oBusk


1 Answers

You can do this instead:

<table ng-init="page.businessRows = page.businessRows || []">

Update

I look at the parser code of AngularJS and notice that version 1.2 (currently RC) supports ternary expression. So if you use AngularJS 1.2, this will also work (although more verbose than the above code):

<table ng-init="page.businessRows = page.businessRows == null ? [] : page.businessRows">

See demo here.

However, your original code might not work if page.businessRows is null, because the parser will fail to dereference length property of null. So just be careful there.

like image 92
Buu Nguyen Avatar answered Oct 26 '22 11:10

Buu Nguyen