简体   繁体   中英

$index giving error on Empty array Angular

I have the following:

<table id="myid" class="class2" style="width: 100%;" >
    <tbody>
        <tr ng-repeat="row in detailCollection.Info"  >

            <td>
                <a class="button " ng-click="fire({{$index}})" ng-show="!ViewMode">Upload</a><input ng-show="false" name="{{'fileSocialUpload' + $index}}" id="{{'fileSocialUpload'+ $index}}" onchange="angular.element(this).scope().setFiles(this)" class="file" type="file"/></td>                     

        </tr>                    
    </tbody>
</table>

And when the array is empty the ngrepeat seems to be evaluation the $index so it throws and error. How to avoid this $index evaluation when array is empty on the ngrepeat?

Your name attribute you are trying to generate with the $index is slightly wrong.

Assuming you are trying to generate the name fileSocialUpload1 for the first element, your syntax should change to:

name="fileSocialUpload{{$index}}"

This can also be applied to how you are generating your elements id attribute value.

id="fileSocialUpdate{{$index}}"

Syntax inside the {{}} isn't normal JS so not all expressions will evaluate the way you might want them to.

Also your use of the onchange element could be easier to read.

onchange="angular.element(this).scope().setFiles(this)"

Can be changed to

ng-change="setFiles($index)"

Avoiding use of .scope to get the scope of an element from the DOM will avoid problems if you move start using directives with isolated scopes or move the onchange attribute to another element.

Knowing how the id is generated you can select the element within the setFiles function using jQuery selector and the passed in $index value.

Likewise for the ng-click , you want to pass in the $index argument, this doesn't have to be evaluated with {{}} to pass into an ng-click .

我使用ng-attr-id="{{ 'fileSocialUpload' + $index }}"找到了解决方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM