Somnath Muluk Somnath Muluk - 2 months ago 16
AngularJS Question

ng-repeat with dynamic ng-include and template variables scope issue

When ng-repeat is having dynamic ng-include with variables, it is not taking variables properly.

See this plunker.

main html code

<table style>
<tr>
<th>Student</th>
<th>Teacher</th>
</tr>
<tbody ng-repeat="val in data">
<tr>
<td>
<div ng-include src="'profile.html'" onLoad="profile=val.student"></div>
</td>
<td>
<div ng-include src="'profile.html'" onLoad="profile=val.teacher"></div>
</td>
</tr>
</tbody>
</table>


profile.html code

<span>Id - {{profile.id}}</span>
<span>Name - {{profile.name}}</span>


You can see at link without ng-include it works perfect.

P.S. This is prototype of what I am actually trying to achieve.
Mainly I am having problem with variables used in dynamic ng-include present in ng-repeat.

I have checked similar questions like below but not getting any answers.

1 2 3

Answer

The ng-include directive does not create a new $scope object, but prototypically inherits it, so your profile is overwritten with another value.

So first you say profile=theStudent and then you overwrite it with profile=theTeacher, therefore in both templates it is always set to the teacher.

There is a little 'hack' to fix this by adding the ng-if="true", which creates a new $scope object:

<tbody ng-repeat="val in data">
    <tr>
        <td>
            <div ng-include src="'profile.html'"
                 onLoad="profile=val.student"
                 ng-if="true"></div>
        </td>
        <td>
            <div ng-include src="'profile.html'" 
                 onLoad="profile=val.teacher"
                 ng-if="true"></div>
        </td>
    </tr>
</tbody>

See this updated plunker