将html标记从控制器传递到angularjs变量 [英] Pass html tag to angularjs variable from controller
问题描述
每次用户输入错误的电子邮件时,我都会尝试执行此验证.我通过这样的html中的变量来处理它:
I have this validations which I am trying to do every time user enters a wrong email. And I am handling it via variable in my html like this:
<p class="error" ng-show="!!user.errorText || form.$submitted">
{{user.errorText}}
</p>
到目前为止,一切都很好,因为我将errorText替换为来自控制器的文本值,如下所示:
So far everything is fine as I am replacing the errorText with text values from my controller like this:
$scope.user.errorText = "Email is incorrect"
现在,我实际上想插入类似<a>
的html标签.例如:
Now, I actually wanted to insert a html tag like <a>
. For example:
$scope.user.errorText = "Email is incorrect . <a href='#'>View Examples</a>"
但是可变的{{user.errorText}}
总是将其重命名为文本.关于如何同时呈现标签和文本的任何帮助都将有所帮助.另外,我无法替换html中的{{user.errorText}}
,因为它已经用于n次验证,并且很少使用html标签.
But the vaiable {{user.errorText}}
is always redering it as text. Any help on how can I render both tags and text would be helpful. Also, I can't replace {{user.errorText}}
in html as it has already been in use for n number of validations and the scenario of using a html tag is rare.
推荐答案
您可以使用ng-bind-html
指令绑定html文本(它也适用于简单文本):
You can use ng-bind-html
directive to bind html text (it will work also for simple text):
<p ng-bind-html="user.errorText"></p>
https://docs.angularjs.org/api/ng/directive/ngBindHtml
如果应用程序中未包含angular-sanitize.js
,则会显示以下错误:
If angular-sanitize.js
is not included in the application, then the following error will show up:
angular.min.js:1错误:[$ sce:unsafe]试图在安全的上下文中使用不安全的值.
angular.min.js:1 Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.
在这种情况下,需要像这样使用$sce
服务:
In that case, $sce
service needs to be used like this:
$scope.user.errorText = $sce.trustAsHtml("Email is incorrect . <a href='#'>View Examples</a>");
这篇关于将html标记从控制器传递到angularjs变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!