Steps for dynamically executing an Angular ng-include directive in real-time

Is there a way to dynamically insert an ng-include element into an HTML page and have it function properly?

I am working on a Drag N Drop application where users can drag an element onto the page, and upon dropping it in the designated zone, the original element is replaced with a more detailed one. For example, dragging a box labeled "Calendar" would display an actual calendar once dropped. It's important to note that this new element is generated and added to the DOM only after the drop event.

After the element is dropped, I am aiming to replace it with a specific chunk of HTML code as shown below. Currently, the markup is hardcoded within a string, which is not ideal:

<div class='panel panel-default'>
  <div class='panel-heading'>
    <h3 class='panel-title'>
      <span class='glyphicon glyphicon-remove'></span>
      WIDGET NAME
      <spanclass='glyphicon glyphicon-cog'></span>
    </h3>
  </div>
  <div class='widgetContainer' ng-include="'widgets/widget.html'"></div>
</div>

However, when this HTML is inserted into the page, the referenced HTML file specified in ng-include is not actually included.

My desired outcome is to load an external HTML file containing the widget markup and include it at the correct position. As a beginner in Angular, I'm unsure if this issue is due to:

  • The lack of support for dynamically adding ng-include elements
  • A need for additional controller logic to handle this process
  • Possibly using the tag instead of the attribute
  • This functionality simply not being feasible.

Please share examples and solutions as I am still learning Angular.

Thank you.

UPDATE

The code snippet responsible for generating the HTML to be dynamically added to the page is as follows:

$("#template").append(
    " \
    <div class='panel panel-default'>\
    <div class='panel-heading'>\
    <h3 class='panel-title'>\
    <span style='padding-right: 10px; cursor:pointer;' class='glyphicon glyphicon-remove' onclick='removeElement(this)'></span>\
    " + widgetDetail['serviceName'] + "\
    <span style='float:right; cursor:pointer;' class='glyphicon glyphicon-cog' onclick='toggleWidgetDetail(this)'></span>\
    </h3>\
    </div>\
    <div class='markupContainer' ng-include=\"'widgets/" + id +".html'\"></div>\
    </div>\
    "
);

You can find the complete code on GitHub. The drag-and-drop functionalities are currently implemented using HTML5 JavaScript, located in the file

/public/javascripts/js_dragndrop.js
. The addition of the new widget to the page (as shown above) is handled in
/public/javascripts/jq_dragndrop.js
.

This project is in the prototyping phase, so expect some rough code as I experiment with DragNDrop elements.

Answer №1

I successfully achieved my desired outcome by transferring the HTML5 drag and drop code into AngularJS directives. With guidance from [ Compiling dynamic templates externally in Angular ], I managed to load the HTML templates where needed.

The key modification in the code is as follows:

angular.element(document).injector().invoke(function ($compile) {

  var widgetDetail = widgets[e.dataTransfer.getData('Text')];

  var obj = $("#template");
  var scope = obj.scope();

  obj.append(
    "<div class='panel panel-default'><div class='panel-heading'><h3 class='panel-title'>\
     <span style='padding-right: 10px; cursor:pointer;' class='glyphicon glyphicon-remove' onclick='removeWidget(this)'></span>\
     " + widgetDetail['serviceName'] + "\
     <span style='float:right; cursor:pointer;' class='glyphicon glyphicon-cog' onclick='toggleWidgetDetail(this)'></span>\
     </h3></div><div class='markupContainer' ng-include=\"'widgets/" + widgetDetail['serviceId'] + ".html'\"></div>\
     "
   );

   $compile(obj.contents())(scope);
   scope.$digest();
});

If you're interested, the complete code can be found in the Git Project /public/controllers/template.js.

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

Using ajax.actionlink to display the desired text

When using an ajax.actionlink @Ajax.ActionLink("Add Last Name", // <-- Text to display "AddTimeSeriesData", // <-- Action Method Name etc.... @id = "link") How can I extract the link text in JavaScript? I attempted to use $(&apo ...

Stop the interval once the route is altered in Angular 2

After initiating a timer within an Angular 2 component located inside a router outlet, I encounter a problem when switching routes. The timer continues to run even after leaving the route. How can I ensure that the timer is properly stopped upon route ch ...

Display a loading dialog when an AJAX request is made

I am working on a Grails application and I would like to implement a visual indicator, such as a modal dialog, to show when an AJAX request is in progress. Currently, I rely on JQuery for all my AJAX requests. While they are triggered using Grails tags at ...

Assistance is required to navigate my character within the canvas

Having trouble getting the image to move in the canvas. Have tried multiple methods with no success. Please assist! var canvas = document.getElementById("mainCanvas"); canvas.width = document.body.clientWidth; canvas.height = document.body.clientHeight; ...

Determine the total number of arrays present in the JSON data

I'm currently working on a straightforward AngularJS project, and here's the code I have so far: This is my view: <tr ng-repeat="metering in meterings"> <td>1</td> <td>{{metering.d.SerialNumber}}</td> ...

Exploring the Significance of jQuery in a Real-

I manage a large website with an extensive amount of jQuery code spread across multiple pages. The total codebase is around 1000 lines, well-optimized and excluding plugins. Despite jQuery being efficient in ignoring listeners for non-existent page elemen ...

Updating the date with setState in Material UI components

I have a question about integrating the material ui datepicker into my project. I want the current date in the state to update whenever the user switches from one date to another. You can find the materialUi datepicker I am using at this link. I tried im ...

Loading external scripts prior to component loading in Vue.js

Within my Vue project, I have the need to fetch a script from a server location (e.g. https://myurl.com/API.js). This script contains a variable that I intend to utilize within my Vue component/view. The issue arises when I attempt to load this script usi ...

Guide on parsing a JSON object in JavaScript

One issue I'm facing is that my controller method returns a string representation of a jsonArray using the jsonArray.toString() function. Below is the corresponding ajax method: function loadPropertyFile(url) { $.ajax({ type: "GET", url: url, ...

Modify the collapse orientation in Bootstrap

I would like the button to expand from the bottom when clicked and collapse back down, instead of behaving like a dropdown. <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_ ...

A guide on ensuring all necessary keys are present in a JSON document using Node.js

I have been researching various methods for efficiently checking if a key exists in a JSON file. The challenge I am facing is related to optimizing this process. My current workflow involves users uploading a CSV file which I then convert into JSON format ...

"Having trouble getting the onChange function to work with Material-UI's Select

I have encountered an issue while trying to implement the material-ui SelectField component in my project. While the common select component works seamlessly, I face problems when using the SelectField component. The main problem arises with the invocati ...

Combining the power of Vuforia with the capabilities of Three

I'm having difficulty with the integration of three.js and Vuforia, as I have limited knowledge about OpenGl which makes it challenging to troubleshoot. Our team is working on a small AR app where we aim to utilize Vuforia for tracking and recognitio ...

Utilizing Google Analytics 4 in a React TypeScript Environment

Currently, there are two options available: Universal Analytics and Google Analytics 4. The reasons why I lean towards using Google Analytics 4: Universal Analytics is set to be retired on July 1, 2023, so it makes sense to start fresh with Google Analyt ...

What is the best way to preload $templateCache before setting up routes in app.config?

Within my AngularJS application, I am currently in the process of constructing a build using grunt along with several essential plug-ins. grunt-contrib-clean grunt-contrib-requirejs grunt-angular-templates grunt-angular-copy I have successfully generat ...

What happens when there is no match found while attempting to edit a form with the UI-Bootstrap typeahead directive?

Here is the code that demonstrates how my typeahead input box functions. Users can enter a name, and the relevant information will populate the rest of the form. If no match is found, users should still be able to input the name and related details into th ...

Using JavaScript's document.write method to display HTML code, along with a variable retrieved from a Flash application

Can I ask two questions at once? Firstly, how can I achieve the following? document.write(' <div id="jwplayer"> <center> <div id='mediaplayer'></div> <script type="text/javascript"> jwplayer('mediapl ...

Avoid revealing sensitive information by refraining from utilizing the Json decode() function

After successfully storing values in an HTML table to a MySQL database, I encountered an issue when trying to fetch the data using Json decode(). The HTML table did not display any data on the web page, and there were no errors thrown. Below is the PHP co ...

Disappearing Query Parameters in POST Requests with Node.js and Express

This is my first attempt at creating a JavaScript client and nodeJS server with Express that communicate using REST API. However, I'm running into an issue where any parameter I pass in the xhttp.send function is not being received on the back-end. O ...

Exploring the power of React's useState and useEffect hooks with JSON data

Just starting out with React. The task I'm tackling involves fetching data from an API (provided in JSON format) and updating the setNavItems with the retrieved JSON response. However, when attempting to iterate over the results using navItems.map, n ...