AngularJS is experiencing an issue where the dynamic partial stored in $templateCache is being removed

It seems like my code is haunted or I've made a mistake:

Here is the structure of a json feed I'm working with:

{
  "sections": [
    {
      "identifier": "header",
      "blocks": [
        {
          "identifier": "onebyone",
          "html": "<h1>API</h1>"
        },
        {
          "identifier": "onebyone",
          "html": "<h1>API</h1>"
        }
      ]
    },
    {
      "identifier": "content",
      "blocks": []
    },
    {
      "identifier": "footer",
      "blocks": []
    }
  ]
}

I'm making a call in my AngularJS controller, sorting the sections, and trying to concatenate the HTML blocks, like this:

cmsApp.controller('cmsPageCtrl', function($scope, $http, $templateCache, $sce) {

    $http.get("/api.php/api/page/home")
        .success(
            function(response) {
                $scope.sections = [];

                response.sections.forEach(function(el, idx, arr) {
                    var id = el.identifier;

                    $scope.sections[id] = el;
                    $scope.sections[id].template = 'header.html';

                    var template = "TEST";

                    el.blocks.forEach(function(el, idx, arr) {

                        var partial = el.html;
                        template = template + partial;
                    });

                    template = template + "<div><b>b</b>TEST1</div>";
                    console.log(id);
                    console.log(template);

                    $scope.sections[id].template = 'header.html';

                    $templateCache.put('header.html', $sce.trustAsHtml(template));
                    console.log(template);

                });
            }
        );
});

Even though the expected output should be:

<body ng-app="cmsApp" ng-controller="cmsPageCtrl">
    <ng-include src="sections.header.template"></ng-include>
</body>

It turns out to be:

<span class="ng-scope">TEST</span><div class="ng-scope"><b>b</b>TEST1</div>

And the console output reveals:

cms.ctrl.js (line 33)    TEST<h1>API</h1><h1>API</h1><div><b>b</b>TEST1</div>
cms.ctrl.js (line 34)    TEST<h1>API</h1><h1>API</h1><div><b>b</b>TEST1</div>
cms.ctrl.js (line 39)    content
cms.ctrl.js (line 33)    TEST<div><b>b</b>TEST1</div>
cms.ctrl.js (line 34)    TEST<div><b>b</b>TEST1</div>
cms.ctrl.js (line 39)    footer
cms.ctrl.js (line 33)    TEST<div><b>b</b>TEST1</div>
cms.ctrl.js (line 34)    TEST<div><b>b</b>TEST1</div>
cms.ctrl.js (line 39)

Why is the HTML being stripped from the header section output?

Answer №1

Angular has a built-in protection mechanism against injection, which is enabled by default. If you still want to allow it, you can do so by installing the ng-sanitize plugin. After that, make sure to include the module in your app:

angular.module('myApp', ['ngSanitize']);

Next, use the ng-bind-html directive to bind your HTML content securely.

ng-bind-html="myHTML"

For more information, you can refer to the official documentation.

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

Creating personalized JSON encoding in Go: A guide

When I tried to customize the encoding format of a struct, I encountered an error message: json: error calling MarshalJSON for type main.Info: invalid character 'o' in literal false (expecting 'a') Can anyone help me identify what&apos ...

Dynamic loading of JavaScript/HTML content using jQuery Mobile and PhoneGap

I am currently in the process of building a mobile app using Dreamweaver CS6 (with PhoneGap), along with jQuery Mobile and JavaScript. This app aims to gather user-inputted form data, convert it into a JSON object, and send it to a python web service. The ...

Tips for Iterating through Nested Arrays using the Inside Array in a Dynamic Way

I am facing an issue with my code as it lacks flexibility when a new array is added to the nested array, in which case the new array is not considered. My main concern is how to access the elements of each nested array simultaneously. Here's an examp ...

How can NodeJS Websocket (ws) facilitate communication between various clients?

In my project, I have a scenario where client1 needs to share information with client2 and the latter should receive an alert upon receiving it. To achieve this, I am utilizing Websocket "ws" with NodeJS. The web page for client1 receives a response via A ...

Ensure that Bootstrap 5.2 tooltips do not close when the cursor returns to the triggering element

TLDR: The tooltip flickers when moving the cursor from the tooltip back to the triggering element. I want the tooltips to open on hover and be clickable. I found a solution that works on Stack Overflow here. When you hover over an element, a tooltip appe ...

The synchronization and network bandwidth optimization of Angular and Firebase's three-way binding system

Is it possible to synchronize the text box content across various clients using Angular and Firebase? I am curious to know if Firebase will update the database with each letter I type. How does this process impact network bandwidth? Can you explain how it ...

Tips for incorporating JSON data from an API into your frontend interface

After following a tutorial on setting up an API with Express and PostgreSQL, I was able to successfully retrieve all my data in JSON format. However, I am now facing the challenge of using this data on the frontend of a website. The code snippets below ar ...

Can you display a popup on a leaflet map from beyond its boundaries?

Utilizing leaflet maps, I have implemented a functionality where clicking on the map opens a popup at a specified location and centers on that position. The code for this is as follows: var popup = L.popup(); function onMapClick(e) { popup . ...

Trigger the datepicker's onselect event programmatically

Does anyone know how to manually trigger the onselect event of a datepicker? My code is currently functioning correctly (retrieving data from a database based on the value of the datepicker's altfield), but I'm having an issue where the onselect ...

The issue of saving Rails input from an Angular2 front end has been causing some trouble

Currently, I am in the process of developing a front-end application using Angular 2 that retrieves data from a Rails 5 API. This specific application serves as a network inventory tool. One particular feature of this app is an Asset-form in Angular2 whic ...

Parallax scrolling in all directions

Is there a resource available for learning how to program a website similar to the one at ? I am familiar with parallax but can't seem to find any examples that resemble what they have done on that site. ...

Getting Creative with Jquery Custombox: Embracing the 404

Encountering a problem with jquery custombox version 1.13 <script src="scripts/jquery.custombox.js"></script> <script> $(function () { $('#show').on('click', function ( e ) { $.fn.custombox( this, { ...

Updating dynamic parameter in a NextJS 13 application router: A complete guide

In my route user/[userId]/forms, I have a layout.tsx that includes a Select/Dropdown menu. The dropdown menu has options with values representing different form IDs. When the user selects an item from the dropdown, I want to navigate to user/[userId]/form ...

Show a message popup or view based on the validation of the model

Picture an online store with multiple steps to complete during the checkout process. Whenever the customer clicks the 'next' button, it triggers the corresponding 'Action' method. This method includes a validation check to ensure that t ...

I am in need of a efficient loader for a slow-loading page on my website. Any recommendations on where to find one that works

I'm experiencing slow loading times on my website and I'm looking to implement a loader that will hide the page until all elements are fully loaded. I've tested several loaders, but they all seem to briefly display the page before the loader ...

Can Puppeteer extract the complete HTML content of a webpage, including any shadow roots?

When using Puppeteer to navigate a webpage, I typically can retrieve the full HTML content as text with this code: let htmlContent = await page.evaluate( () => document.querySelector('body').innerHTML ); However, I am currently faced with ...

Tips for verifying the contents of a textbox with the help of a Bootstrap

I am still learning javascript and I want to make a banner appear if the textbox is empty, but it's not working. How can I use bootstrap banners to create an alert? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&g ...

A guide on accessing URL query parameters using AngularJS

Is it possible to extract specific URL parameters using AngularJS and then assign their values to textboxes? For instance, a sample URL would be: http://example.com/?param1=value1 I've come across examples involving $location, routing, and services ...

Converting PHP variables to JavaScript using AJAX and XML communication

In order to gain a deeper understanding, I am determined to tackle this task without relying on jQuery. This means I am willing to reinvent the wheel in order to fully comprehend how it functions. My research has led me to believe that AJAX is the key to a ...

Integrating dual Google Maps onto a single HTML page

I'm facing an issue with implementing two Google maps on a single page where the second map seems to be malfunctioning. Below is the code I am currently using: <style> #map-london { width: 500px; height: 400px; } #map-belgium { wi ...