Display the HTML content from Angular's variable stored in the scope

While I am mindful of the security implications, I require permission for a special super admin group of users to have the ability to generate and assess angular html embedded within variables in the current $scope

For an example, please refer to this plunk:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f1e11180a131e0d51150c3f4e514c5107">[email protected]</a>" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl" ng-init="variable = 3; content = '{{ variable }}'">
    <div>
      The value of $scope.variable === "{{ variable }}"
    </div>
    <div>
      The value of $scope.content === "{{ content }}"
    </div>
    <br>
    <div>
    The value of $scope.content is <b>ng-model</b>'ed via the following textarea:<br>
    </div>

    <textarea rows="3" ng-model="content"></textarea>

    <div style="border: 1px solid black">
      Instead of rendering the value of the $scope.content field which is currently equal to "{{ content }}" I need to render compiled and evaluated value which should be equal to "{{ variable }}"
    </div>
  </body>

</html>

Any recommendations are appreciated.

Many thanks in advance!

Answer №1

If you want to simplify the process, consider creating a directive that utilizes the $compile service.

I have crafted a solution for you, and you can view it in action by checking out this modified version of your Plunkr project.

app.directive('compile', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      var prevScope;
      scope.$watch(attrs.compile, function(newVal, oldVal) {
        // create a span element to hold the HTML content
        var newElem = document.createElement('span');
        newElem.innerHTML = newVal;

        // cleanup previous scope if exists
        if (prevScope) {
          prevScope.$destroy();
          prevScope = null;
        }
        
        // clear existing contents
        elem.empty();
        
        // append the raw HTML node
        elem[0].appendChild(newElem);
        
        // compile the node with an isolated child scope
        try {
          prevScope = scope.$new();
          $compile(newElem)(prevScope);
        } catch (e) { /* error handling code goes here */ }
      });
    }
  }
});

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

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

Tips for effectively eliminating errors in a redux store

Within my react-redux application, I have implemented a system to catch error responses from redux-saga. These errors are saved in the redux-store and rendered in the component. However, a major challenge arises when trying to remove these errors upon comp ...

Include all the items from the directory into the array in the form of an object

https://i.sstatic.net/48gCi.png I am currently dealing with a file structure similar to the one shown in the image, and I have code that reads folders content as follows: var array = [] fs.readdir(__dirname + '/static/katalogi', function (err ...

Issue with Knockout.js: Parsing error in bindings - SyntaxError: Unexpected token `};`

Take a look at this example. I've tried to simplify it as much as possible, but I'm still struggling to figure out where I went wrong. Any help would be greatly appreciated )) P.S Stack Overflow requires code, not just a link to jsfiddle. H ...

Access local files by utilizing iframe

I attempted to load files via an iframe, however, it was unsuccessful. I am attempting to load a file from: C:/Users/Tom/Desktop/Courses/c2.pdf and I tried: <iframe src="file:///C:/Users/Tom/Desktop/Courses/c2.pdf></iframe> Unfortunately, no ...

What could be the reason for the unrecognition of the callback function within the directive controller

I am attempting to make a directive work with its own controller: http://jsfiddle.net/edwardtanguay/xfbgjun5/14/ However, when I click the button: var template = '<button ng-click="vm.addItem()">add item</button>'+ & ...

Leverage the controller's properties and methods within the directive

My situation involves a variety of inputs, each with specific directives: <input mask-value="ssn" validate="checkSsn"/> <input mask-value="pin" validate="checkPin"/> These properties are managed in the controller: app.controller("Ctrl", [&ap ...

Accessing information through API in Javascript

I am looking to retrieve data from an API by connecting to it through the Hubspot CMS. The API link can be found here: Despite trying a Codepen example, I am facing difficulties as the data is not displaying even though there are no errors in the console: ...

I continue to encounter the error "Unexpected token b in JSON at position 0" when attempting to parse JSON data

Having some trouble with my code that generates an HTML page. The signup function allows users to register and create a password, while the checkpassword function is supposed to verify if the correct password is entered for the given username. I seem to be ...

Add elements to an array following an AJAX request

On my .cshtml page, I have the following script: $(function () { var tempArray = []; var tbValue = $('#tb1').val(); $.ajax({ url: "/ControllerName/getdata", dataType: 'json', ...

Splicing using only one parameter will make changes to the array without deleting the entire array

let myArray = ['a','b','c','d','e']; console.log(myArray.splice(1)); console.log(myArray); Looking at the splice documentation, it mentions that not providing a delete parameter would remove all array item ...

Utilize the dimensions of one image to resize others using the JavaScript method .getBoundingClientRect

I am attempting to transfer the width and height measurements of the initial image to all subsequent images on the page. Currently, I have successfully applied the dimensions of the first image to the second one, but I am facing difficulties with the thir ...

JavaScript's inability to properly export CSV data containing the "#" character has been causing issues

When exporting JSON data to CSV format and downloading it using JavaScript, everything typically works fine. However, there is a problem if the data contains the hash sign #. The function fails to export all the data in that case, for example: This is my ...

What is the reason behind JavaScript libraries opting for a structure of [{ }] when using JSON?

I have been experimenting with various Javascript libraries, and I've noticed that many of them require input in the format: [{"foo": "bar", "12": "true"}] As stated on json.org: Therefore, we are sending an object within an array. With this observ ...

Is there a way to prevent a 'keyup' event from being triggered by a 'keydown' event?

I have a tool that resolves zip codes and I am currently utilizing a keyup event handler to trigger a server query once the input length reaches 5 characters. However, I want to prevent unnecessary calls to the script, so I am exploring the possibility o ...

Organizing files on a website for collaborative projects involving multiple team members

I am currently constructing a website with the following specifications: Pages are being loaded inline via AJAX. CSS, HTML, JavaScript, and PHP are all separated to facilitate collaboration on projects. While working on creating a dynamic <select> ...

I am attempting to establish a connection with the Converge Pro 2 system from Clearone using NodeJS node-telnet-client, but unfortunately, my efforts to connect have been unsuccessful

My connection settings are as follows: { host: '192.168.10.28', port: 23, shellPrompt: '=>', timeout: 1500, loginPrompt: '/Username[: ]*$/i', passwordPrompt: '/Password: /i', username: 'clearone ...

Node.js promise not returning expected value

In this scenario, I have created the loginUser model to verify if the user exists or not. The code is functioning properly, however, I am encountering an issue with the isValidPassword function. It always returns a false condition, even when the email and ...

Two-way binding with Angular2's NgModel can encounter issues

After executing a GET XMLHttpRequest against a service, I received the following JSON payload as a response : {_id: "5aa1358d32eba9e34dd9f280", source: "Avengers", target: "Iron Man", enemies: "Actor"} Within my src/app directory, I have defined the obje ...

Get the contents inside the window.open using Javascript

First and foremost, I want to acknowledge that I understand the likelihood of this failing due to cross-domain restrictions - just seeking confirmation on that. Here's my approach: I have a window that I open using JavaScript. Subsequently, I make an ...