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:
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;
}
}
}
});