Ways to showcase an array with HTML content in AngularJS without using ng-repeat

Can someone help with this coding issue?

"elements" : ["<p>Element 1</p>","<span>Element 2</span>"]

I want to achieve the following output:

<div id="wrapper">
    <p>Element 1</p>
    <span>Element 2</span>
</div>

Is there a way to accomplish this without relying on ng-repeat ?

Answer №1

If you want to display content directly, you can do it like this:

$scope.itemsToShow = {"items": ["<p>Item 1</p>", "<span>Item 2</span>"]};

     <div ng-bind-html-unsafe="itemsToShow.items"> </div>

Alternatively,

you can use $sce.

.controller('controllerName', ['$scope', '$sce', function ($scope, $sce) {
   $scope.itemsToShow = {"items": ["<p>Item 1</p>", "<span>Item 2</span>"]};
   $scope.newItems= $sce.trustAsHtml($scope.itemsToShow.items);
  }]);

  <div ng-bind-html="newItems"> </div>

Answer №2

If you're working with AngularJS, one way to display HTML content is by using the ng-bind-html directive along with the $sanitize service.

To pass an array as an HTML string in your view, you can utilize the Array.prototype.join() method:

angular
  .module('App', ['ngSanitize'])
  .controller('AppController', ['$scope', function ($scope) {
    var obj = {
      "items": ["<p>Item 1</p>","<span>Item 2</span>"]
    };
    $scope.items = obj.items.join('');
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.10/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.5.10/angular-sanitize.min.js"></script>

<div ng-app="App" ng-controller="AppController">
  <div id="container" ng-bind-html="items"></div>
</div>

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

Unable to display the column data labels in Highcharts due to the incorrect formatting being presented

I'm having trouble displaying the datetime format at the top of a column in my chart. Although the tooltip shows the correct data when hovering over the columns, the labels are not formatted properly. Received output - 86340000 Expected output - 23: ...

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

JavaScript code that displays items in a shopping cart

I've set up the HTML and JS functionality for the cart, but I'm facing an issue where the JS doesn't render the cart items when the shop item is clicked. The styling in my HTML is done using Tailwind. If anyone could provide some assistance ...

Error Occurred while Uploading Images using Ajax HTML Editor with JSON Data

I am facing an issue with my AJAX HtmlEditorExtender, specifically when trying to upload an image. The error message I receive is as follows: JavaScript runtime error: Sys.ArgumentException: Cannot de-serialize. The data does not correspond to valid JSON. ...

`In AngularJS, the default selection option is not functioning as expected`

I'm struggling with a particular issue in my code. <select ng-model="selected_student" class="form-control"> <option ng-repeat="obj in students" value="{{obj.id}}">{{obj.name}}</option> </select> When I try to set the sel ...

Webpack 4.1.1 -> The configuration.module contains a property 'loaders' that is unrecognized

After updating my webpack to version 4.1.1, I encountered an error when trying to run it: The configuration object is invalid. Webpack has been initialized with a configuration that does not match the API schema. - The 'loaders' property in ...

Unforeseen anomalies arise when deleting an element from an array in a React application

I've been scouring for a solution, but I could really use some human guidance. I have a basic form where users can input additional fields. They also have the option to delete irrelevant fields. The problem arises when trying to remove these fields. ...

Move the location of the mouse click to a different spot

I recently received an unusual request for the app I'm developing. The requirement is to trigger a mouse click event 50 pixels to the right of the current cursor position when the user clicks. Is there a way to achieve this? ...

How to use jQuery to remove a class from the last entered data in a form

Reminder: This is a jQuery coding challenge, and I am required to write the validation script without using any plugins or additional modules. I have created a basic form validation script. If a user inputs data that is empty, an appropriate error message ...

Simulated function for handling express functions

I'm currently working on a server.js file that includes an app.get function. To test this function using "jest", I am having trouble writing a mock function for the app.get implementation shown below. app.get('/api/getUser', (req, res) => ...

What prevents me from calling a function while it is being defined in the prototype?

I am experimenting with inheritance through an example. I want to access all properties of objects abc and pqr, so I decided to use Object.create. However, when I try to get the value of r by calling the getr() function, it doesn't seem to work as exp ...

What could be causing the target to malfunction in this situation?

Initially, I create an index page with frames named after popular websites such as NASA, Google, YouTube, etc. Then, on the search page, <input id="main_category_lan1" value="test" /> <a href="javascript:void(0)" onmouseover=" window.open ...

What is the process for launching a new terminal within Node.js?

I'm seeking advice on creating a secondary window in my node.js application where I can output text separate from the main application. Imagine having a main window for displaying information and a secondary window specifically for errors that closes ...

Unable to import local npm package due to an error

We are in the process of migrating multiple websites, each with its own project, to Vue.js. As we transfer files over and bundle them using Webpack, we have encountered a need to consolidate similar components and core JavaScript files into a shared librar ...

Ensure that the user remains within the current div when they click the submit button, even if the textbox is

For the past 48 hours, I've been grappling with an issue on my HTML page that features four divs. Each div contains three input fields and a button. The problem arises when a user leaves a text box empty upon submitting - instead of staying in the sam ...

How can you create a personalized sorting order using odata?

Within my AngularApp, I retrieve data from a WebAPI using OData queries. All the retrieved results contain both a date and an integer status code. The status codes range from 1 to 4. I am aiming to organize my results in such a way that all items with a ...

What is the purpose of employing useMemo in the Material-UI autocomplete documentation?

My focus is on this specific demo in the autocomplete documentation. In the google maps example, there is a throttled function that is returned from a useMemo with an empty array as the second parameter. However, it raises the question of what exactly is ...

Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links. Here is a snippet of my JavaScript code: $(document).ready(function() { var attr = $(&apos ...

Troubleshooting issues with jQuery `.live()` event not triggering as expected

In a project I am working on, I have implemented complex AJAX functionality to fetch inner page content from a WordPress blog. Due to the dynamic nature of the site, where the DOM is replaced after page load via AJAX, I have opted to use jQuery's .liv ...

What is a more efficient method for switching between edit mode and view mode in ng-grid?

Up until now, I've only managed to switch the edit mode in ng-grid by using separate templates and showing the correct template based on user input. For example: Plunker (resize a column and then switch to another mode) This poses a problem because ...