Problematic situation when using ng-repeat with dynamic ng-include and template variables scope conflict

When utilizing ng-repeat with dynamic ng-include that includes variables, the variables are not being properly recognized.

Take a look at this code snippet.

Here is the 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>

And here is the profile.html code:

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

Without using ng-include, everything works perfectly fine.

P.S. This is just a prototype of my desired functionality. I am specifically struggling with getting variables to work in dynamic ng-include within ng-repeat.

I have reviewed similar questions like these ones but haven't found any solutions:

1 2 3

Answer №1

When using the ng-include directive, it's important to note that it does not create a new $scope object. Instead, it prototypically inherits from the existing one, which can lead to unintentional overwriting of values. In this case, if you set profile=theStudent and then overwrite it with profile=theTeacher, the profile will always be set to the teacher in both templates.

To work around this issue, you can use a little 'hack' by adding the ng-if="true" attribute, which forces the creation of 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>

For an updated example, you can refer to this plunker

Answer №2

Instead of using both ng-include and ng-if directives to achieve the desired outcome, a simpler approach is to create a custom profile directive with an isolated scope and pass data into it.

Plunker demo

angular.module('ng-include-example', []).
controller("MainCtrl", function($scope) {

  var data = [
       {
         "student" : { "id":11, "name": "John" },
         "teacher" : { "id" : 21, "name": "Mike"}
       },
       {
         "student" : { "id":12, "name": "Tony" },
         "teacher" : { "id" : 22, "name": "Jack"}
       },
       {
         "student" : { "id":13, "name": "Cris" },
         "teacher" : { "id" : 23, "name": "Anthony"}
       },
       {
         "student" : { "id":14, "name": "Greg" },
         "teacher" : { "id" : 24, "name": "Reva"}
       }

    ];

    $scope.data = data;

})
.directive("profile", function(){
  return{
    restrict:'E',
    scope:{
      profile: "="
    },
    templateUrl: "profile.html"
  }
});

<div>
  Using Directive
  <table style>
      <tr>
        <th>Student</th>
        <th>Teacher</th>
      </tr>
      <tbody ng-repeat="val in data">
        <tr>
          <td>
            <profile profile = "val.student"></profile>
          </td>
          <td>
            <profile profile = "val.teacher"></profile>
          </td>
        </tr>
      </tbody>
    </table>
  </div>

Answer №3

To improve your coding experience, consider creating a separate HTML file named profile.html and then incorporate it into your code as shown below:

index.html

<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="'profile2.html'" onLoad="profile2=val.teacher"></div>
          </td>
        </tr>
      </tbody>

profile2.html

<span>ID - {{profile2.id}}</span>
<span>Full Name - {{profile2.name}}</span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Get the large data file in sections

I ran a test script that looks like this: async function testDownload() { try{ var urls = ['https://localhost:54373/analyzer/test1','https://localhost:54373/analyzer/test2'] var fullFile = new Blob(); for (le ...

Submitting a form with JQuery and Ajax technology

I am encountering an issue where I need to submit a form within Ajax and I keep getting a 'form.submit is not a function' error in jQuery. $("#form").validate({ // Define validation rules rules: { type: "required", group ...

When scrolling, dynamically change the background color by adding a class

I am looking to achieve a scroll effect where the color of the menu buttons changes. Perhaps by adding a class when scrolling and hitting the element? Each menu button and corresponding div has a unique ID. Can anyone suggest what JavaScript code I should ...

Receive real-time price updates from Next.js using GetServerSideProps data

I'm currently working on fetching live bitcoin prices from CoinGecko. In my index.js file, I have an async GetServerSideProps function that is functioning correctly. The returned props are then passed down to the <Home /> component, and subseque ...

Firebase onSnapshot error when retrieving data from Snapchot

Having trouble with Firebase authentication. Whenever I try to authenticate with Firebase, I encounter this error message: App.js:27 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'onSnapshot') Here is the code sni ...

Generate a new style element, establish various classes, and append a class to the element

Is there a more efficient solution available? $("<style>") .attr("type", "text/css") .prependTo("head") .append(".bor {border:2px dotted red} .gto {padding:10px; font-size:medium}"); $("input:text").addClass("bor gto").val("Enter your t ...

Transforming JSON data into XML using Angular 7

It turns out the xml2js npm package I was using doesn't support converting JSON to XML, which is exactly what I need for my API that communicates with an application only accepting XML format. In my service file shipment.service.ts import { Injecta ...

Display different text based on the property value

I need to display different text based on the value of a property, showing "offline" if camera.key is null and "online" otherwise. Here's the template I'm using: <h3>Camera sensors</h3> <table> <th>Name</th> ...

Exploring the secure synergy between Laravel 5.5 Passport client_secret and Vue JS authentication

Greetings to all, Currently, I am delving into the world of Laravel Passport and Vue.JS (standalone) simultaneously. In my authentication process, I am utilizing the Password Grant Token. An issue that has come up is the necessity for keeping the secret_ ...

Encountering a bindings issue when trying to utilize libxml-xsd within an electron application

Seeking guidance on validating an XML file against its schema within an electron application. Prior to adding the 'libxml-xsd' require statement to my angular2 service, it functioned properly. However, upon inclusion of this statement: const xs ...

Pull in class definitions from the index.js file within the node_modules directory

In my project, I have the package called "diagram-js" in the node_modules. The file node_modules/diagram-js/lib/model/index.js contains multiple class definitions as shown below: /** * @namespace djs.model */ /** * @memberOf djs.model */ /** * The b ...

Implementing long-lasting login functionality in React using JSON Web Tokens

Currently, I have developed an application using React client/Express API with functioning Authentication. Users are able to register and login successfully. My next step is to implement persistent login using JWT tokens so that when a user accesses the U ...

Displaying interactive charts in a pop-up window using Highcharts within a Bootstrap

I am looking to display a highchart inside a popover. Check out my code in this jsfiddle http://jsfiddle.net/hfiddle/abpvnys5/47/. Here is the HTML: <ul class="stat_list" style="float: left;"> <a data-toggle="popover" data-trigger="hover ...

Errors in socket.on Listeners Result in Inaccurate Progress and Index Matching for Multiple Video Uploads

Is there a way to make sure that the `socket.on('upload-progress')` listener accurately updates the upload progress for each video as multiple videos are uploaded simultaneously? Currently, it appears that the listener is updating the progress fo ...

Fade-in effect applied to images upon exposure

Is there a way to fade in an image based on the percentage scrolled, rather than a set number of pixels? I want my website to be responsive and adjust to all screen resolutions. Or perhaps is there a method to have the image fade in when it enters the fiel ...

Getting the Value from a Promise into a Variable in a React Component

I am currently immersed in a React project where I am utilizing the Axios library to retrieve data from an API and store it in a variable. After scouring the internet, it seems that the only method available is through Promise.then(), but this approach si ...

Tips for ensuring a consistent highlight for an active link in Bootstrap

Does anyone have a solution for maintaining highlighted links on a web page? <div id="productnav"> <nav> <ul class="nav"> <li><a href="<?php echo $prefix; ?>pages/one.php?category=1" id="navelement1"<?php if ($c == 1) e ...

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...

The anchor tag is not being used in the function call in an Angular application

Having trouble with calling the logout function inside the login controller. The setup involves a simple login and logout system using ui-router. After successfully logging in and navigating to another page, I encountered issues with calling the logout fu ...

Having an issue while running the command "npm start" in Visual Studio with React.js

PS C:\Users\PC1\Downloads\portfolio_website-STARTER> npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d0d120f091b12111412220a181f0e140918500e091c0f09180f3d4c534d534d">[email protect ...