Thursday, January 19, 2017

AngularJS ng-repeat creates a hashKey for the items in the loop

Scenario:
You load data from an Xml file and display it on your web page. You use a angular repeater (ng-repeat) to loop through the data blocks in the Xml file. After the user changes the input values you submit the data back for saving (may be back to a SharePoint document library to update the residing Xml file).

Result:
When trying to save the file back, you get an error as "Input string was not in a correct format". The Xml file in the SP library does not get updated.

Cause: 
When you inspect the updated Xml you may see that there is a hash key generated for each item with in the Xml blocks where we used the repeater.

 Example:

<Block>
   <Details>
     <Record></Record>
     <Description></Description>
     <Duedate></Duedate>
     <Cost></Cost>
   </Details>

   <$$hashKey>object:94</$$hashKey>
</Block>

<Block>
   <Details>
     <Record></Record>
     <Description></Description>
     <Duedate></Duedate>
     <Cost></Cost>
   </Details>

   <$$hashKey>object:95</$$hashKey>
</Block>

In the page your repeater attributes might look like below:

<div ng-repeat="Block in vm.data.Block">

The reason why the hash keys are generated is, because AngularJS needs to keep track of the items with in the repeater, so that it can update the DOM when necessary.

Solution:
Use a child node inside the block to keep track of the items in the repeater. You can use "track by" for this purpose. Since this provides a tracking mechanism, AngularJS will not generate the hash keys anymore.

Example 1:
<div ng-repeat="blockItem in vm.data.Block track by blockItem.Record">

Note that here I have used Record field which is unique. If you don't have any such child nodes having unique values, use the below code

Example 2:
<div ng-repeat="blockItem in vm.data.Block track by $index">


10 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Online Assignment Help Tasmania - Australia Best Tutor is responsible for providing an excellent range of Online Assignment help Tasmania to the students pursuing different subjects as part of their studies.

    Read More : http://prsync.com/australia-best-tutor/get-good-grades-by-using-the-online-assignment-help-tasmania-2589126

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. This comment has been removed by a blog administrator.

    ReplyDelete
  6. This comment has been removed by a blog administrator.

    ReplyDelete
  7. This comment has been removed by a blog administrator.

    ReplyDelete
  8. This comment has been removed by a blog administrator.

    ReplyDelete
  9. This comment has been removed by a blog administrator.

    ReplyDelete