AngularJS将文本转换为HTML标签

时间:2018-12-14 08:39:16

标签: javascript html angularjs

好的,所以我正在学习AngularJS,其中一项功能是允许用户在文本区域中键入HTML代码,然后将其发送到Controller并存储在code变量中。当用户按下按钮来测试代码时,我希望将文本插入HTML文档中。当前,它所做的只是将其添加为纯文本,而不是呈现它。

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 = '';
  }

  }]
  });

只需澄清一下,按一下按钮就可以了,按一下按钮,数据就成功地从代码添加到codeShow了,它可以显示它,但是显示为明文而不是呈现。谢谢

1 个答案:

答案 0 :(得分:4)

尝试

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

另外,请参考https://docs.angularjs.org/api/ngSanitize/service/ $ sanitize以便更好地实施

相关问题