如何从ngModel渲染HTML标签? [英] How to render HTML Tags from ngModel?

查看:642
本文介绍了如何从ngModel渲染HTML标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AngularJS将JS变量绑定到我的HTML内容,并且工作正常。

I'm using AngularJS for binding JS variables to my HTML content, and it works fine.

JS

var app = angular.module("Tabs", [])
  .controller("TabsController", ['$scope', function($scope){
    $scope.events = my_JS_object;
  })

HTML

<div>{{events.test}}</div>

只要 my_JS_object.test 是一个简单的字符串,例如Hello World,但是一旦我尝试在其中放置HTML标签,例如 Hello< b> World< / b> 它不使用标签作为HTML元素,而是简单的文本。这是有道理的,只有我不知道如何使HTML标签工作。

It works as long as my_JS_object.test is a simple string, like "Hello World", but once I try to put HTML tag in there, such as Hello <b>World</b> It doesn't use the tags as HTML elements, but as simple text. Which makes sense, only I have no idea how to make the HTML tags work.

推荐答案

如Angular文档所述,您可以使用内置的 ng-bind-html 指令来评估模型字符串并将生成的HTML插入元素。

As stated by Angular documentation, you can use inbuilt ng-bind-html directive to evaluate model string and insert resulting HTML into element.

示例:
如果您有模型值如:

Example: If you have model value like:

$scope.myHTML =
 'I am an <code>HTML</code>string with ' +
 '<a href="#">links!</a> and other <em>stuff</em>';

使用 ng-bind-html ,如:

<p ng-bind-html="myHTML"></p>

有关详细信息,请访问: https://docs.angularjs.org/api/ng/directive/ngBindHtml

For detailed information go through: https://docs.angularjs.org/api/ng/directive/ngBindHtml

注意:请勿忘记在您的应用中注入 ngSanitize 服务。

Note: Don't forget to inject ngSanitize service in your app.

这篇关于如何从ngModel渲染HTML标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆