我有一个包含已解码 HTML 实体的字符串:
'ó'
ó
我需要通过 ng-model
值在输入元素中显示此字符串
,但将其与字符一起显示,而不是与解码后的实体一起显示。我尝试过将 $parser
与 $sce
一起使用,但这似乎不起作用。
我尝试了几种不同的方法,但似乎没有效果
.controller('myCtrl', function($scope, $sce){
$scope.char = $sce.trustAsHtml('ó')
})
.directive('trustedHtml', ['$sce', function($sce) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(value) {
console.log(value)
return $sce.trustAsHtml(value);
});
}
}
}])
有什么想法吗?
<小时/>working plunker以下基于@Meiko的回答
最佳答案
你必须对字符串进行 htmlDecode:
function htmlDecode(input){
var elem = document.createElement('div');
elem.innerHTML = input;
return elem.childNodes.length === 0 ? '' : elem.childNodes[0].nodeValue;
}
为了使您的示例正常工作,请使用格式化程序而不是解析器:
ngModel.$formatters.push(function(value) {
return htmlDecode(value);
});
angular.module('test', [])
.controller('myCtrl', function($scope, $sce){
$scope.char = $sce.trustAsHtml('ALK-Abelló A/S')
})
.directive('trustedHtml', ['$sce', function($sce) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$formatters.push(function(value) {
function htmlDecode(input){
var elem = document.createElement('div');
elem.innerHTML = input;
return elem.childNodes.length === 0 ? '' : elem.childNodes[0].nodeValue;
}
return htmlDecode(value);
});
}
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="test">
<div ng-controller="myCtrl">
ALK-Abelló A/S <br>
<input trusted-html ng-model="char"/>
</div>
</body>
</html>
关于javascript - ng-model 中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785346/