I have a use case, where we can have '&#' characters inside of a JSON.
Name: "Kenneth Hinsvark & Maurice McAlister"
Address: "555555 W. Canyon Dr # B212"
The string values are pulled back from a database. Apparently the values were saved to the DB with HTML encoding. I need to able to display the data in a textField without the HTML characters.
My main requirement is that input fields values be converted to plain text.
Name: <input type="text" ng-model="user.name" escape-to-plain-text></input>
Address: <input type="text" ng-model="user.address" escape-to-plain-text></input>
How can I translate the input values to plain text?
Using $sce isn't working for me
$scope.user.name = $sce.trustAsHtml('555555 W. Canyon Dr # B212');
Working Code Example:
Right. So you need a couple of things:
ngSanitize
into your module. ng-bind-html
on the element you want to output the $sce
result. I've edited your fiddle here. - last line outputs the correct # character
Because it outputs HTML, you'd need to grab the contents and parse them to put them in an input.. so maybe in that sense you'd be better off with just doing a match() on the text values to look for HTML entities.
The ngSanitize solution works well for display fields but not for edit/input fields.
I was able to answer my primary question of converting HTML to plain text in a input field by creating a custom directive. Solution posted on js-fiddle
http://jsfiddle.net/egrendon/xa8cseoc/22/
var app = angular.module('myApp', ['ngSanitize']);
app.controller('LoginController', function ($scope, $sce) {
// This object is fected from a DB. The data is stored DB this way....
$scope.user = {
name : "Kenneth Hinsvark & Maurice McAlister",
address : "555555 W. Canyon Dr # B212"
};
$scope.sample = $sce.trustAsHtml('555555 W. Canyon Dr # B212');
});
app.directive('escapeToPlainText', function () {
return {
require: 'ngModel',
link : function(scope, element, attrs, ngModel) {
scope.$watch(function(){return ngModel.$modelValue;}, function(newValue, oldValue){
if (newValue && newValue.length > 0) {
var hasEncodedHTML = newValue.indexOf("&#") > -1;
if (hasEncodedHTML){
var encodedValue = newValue;
var decodedValue = decodeHTMLtoPlainText(encodedValue);
ngModel.$setViewValue(decodedValue);
ngModel.$render();
console.log(decodedValue);
}
}
}, true);
function decodeHTMLtoPlainText(aValue) {
var elem = document.createElement('div');
elem.innerHTML = aValue;
return elem.childNodes[0].nodeValue;
}
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.