GoodDisplayName
GoodDisplayName

Reputation: 78

AngularJS Convert Text to HTML Tags

Okay so I am learning AngularJS, and one functionality is to allow the user to type HTML code into a textarea, this gets sent to the Controller and stored in a code variable. When the user presses the button to test the code, I want the text to be inserted into the HTML document. Currently all it does is add it as plain text, so not rendering it.

test-code.template.js:

<button type="button" class="btn btn-primary" ng-click="$ctrl.showCode()">Test Code</button>
<button type="button" class="btn btn-primary" ng-click="$ctrl.clearCode()">Reset All</button>

{{$ctrl.codeShow}}

test-code.component.js:

angular.
  module('phonecatApp').
  component('testCode', {
    templateUrl: 'Components/test-code/test-code.template.html',
    controller: [function TestCodeController() {
      var self = this;

  self.code = '';
  self.codeShow = '';

  self.showCode = function showCode()
  {
    self.codeShow = self.code;
  }

  self.clearCode = function clearCode()
  {
    self.codeShow = '';
    self.code = '';
  }

  }]
  });

Just to clarify, pressing the buttons do work and the data is successfully added from code to codeShow on the button press, and it can display it, but it is displayed as clear text instead of rendering. Thank you

Upvotes: 1

Views: 1297

Answers (1)

Shashank Vivek
Shashank Vivek

Reputation: 17504

Try

 <div ng-bind-html="$ctrl.codeShow"></div>

also, do refer https://docs.angularjs.org/api/ngSanitize/service/$sanitize for better implementation

Upvotes: 4

Related Questions