使用ng-bind-html添加文本字段

Add text field using ng-bind-html

本文关键字:字段 文本 添加 ng-bind-html 使用      更新时间:2023-09-26

我正试图使用ng-bind-html在"p"标记内创建一个文本字段。它不是渲染输入标记,而是渲染其他标记。

<!doctype html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-sanitize.min.js"></script>
</head>
<body>
<div ng-app="ss" ng-controller="formController">
<p ng-bind-html="hh"></p>
</div>
<script>
var myApp = angular.module("ss", ['ngSanitize']);
function formController ($scope) {
    $scope.hh="<b>Hello</b><input type='text'> ";
}
</script>
</body>
</html>

在输出中,我得到了粗体文本"Hello",但没有得到输入字段。

(我知道我可以把文本字段直接放在html中,但出于某种原因我需要它)

这是因为ngSanitize认为<input>不安全。如果你无论如何都想这样做,你必须明确地相信它:
.controller('formController', function ($sce, $scope) {
    $scope.hh = $sce.trustAsHtml('<b>Hello</b><input type="text" />');
}

另请参阅简短演示


顺便说一句,你应该正确地注册你的控制器(使用.controller()),因为在最新版本的Angular中,在全局对象中查找它们是不推荐的。