I have a text like:
Blablabla
Hello
How are you?
But it has to be stored in my database in the same text field like this:
Blablabla Hello How are you?
I am using Angular and I would like to know how to format the database text before displaying it inside the template like this.
<p>{{ value }}</p>
I know I should add a separator in the database but I don't know if it's possible to add a '\n' for example and then format the text before displaying it.
Try this
In your controller
$scope.value = $scope.value.replace(/\n/g, '<br/>');
$scope.trustedHtml = $sce.trustAsHtml($scope.value);
in your view
<p ng-bind-html="trustedHtml"></p>
OR
you can create a factory to use it everywhere
angular.module('app').filter('trustedHtml', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
});
In your controller
$scope.value = $scope.value.replace(/\n/g, '<br/>');
in your view
<p ng-bind-html="value | trustedHtml"></p>
SOLUTION:
<p ng-bind-html="value"></p>
So Angular $sanitize deletes the tags that may be malicious like 'script'
I'm trying to make a custom filter that replaces new lines with <br/>, like this:
angular.module('appFilters', []).filter('break_lines', ['$sce', function($sce) {
return function(input) {
return $sce.trustAsHtml(input.replace(/\n/g, "<br />"));
};
}]);
And use it in a template like this:
<div class="home-tag">{{locales.home_tagline | break_lines}}</div>
The problem is that the resulting text is html escaped.
Try
<div class="home-tag" ng-bind-html="(locales.home_tagline | break_lines)"></div>
Hope it helps
Angular $sce service seems to be encoding characters and not trusting the html. Is there an option to have the html trusted?
$scope.text = $sce.trustAsHtml('it's broken')
An example.
<p>it's working</p>
<p>{{ text }}</p>
Looks like.
it's working
it's broken
I'd rather not use ng-bind-html because it's meant to be used in a filter like the following.
{{ text | render }}
It is not the $sce that encode your html, actually nothing does that.
But when you use an interpolation {{ text }}, angular will detect that and replace it with a correct value via textNode.nodeValue, not something like innerHTML. Therefore, your ' will be treated as a normal text, not an encoded HTML entity.
That's why the ng-bind-html exists, and nothing prevent you from using the filter inside the ng-bind-html expression.
<div ng-bind-html="text | render | trustAsHtml"></div>
Example filters:
.filter('render', function () {
return function (value) {
return value + '!';
};
})
.filter('trustAsHtml', function ($sce) {
return function (value) {
return $sce.trustAsHtml(value);
};
})
Example Plunker: http://plnkr.co/edit/F8OQvoSzOR06TPepc2Fo?p=preview
Is anyone can tell me is it possible to call filter from other filter in AngularJS.
If it not possible do any one know if it possible to call service from filter ?
From the docs
In HTML Template Binding:
{{ filter_expression | filter : expression : comparator}}
In JavaScript:
$filter('filter')(array, expression, comparator)
So you can use the second notation to call your second filter from the first, in JavaScript, by injecting $filter.
app.filter('filterA', function($filter) {
return function(text) {
return $filter('filterB')(text);
}
});
Usage shown in the docs here.
Edit:
As noted, you can also inject filters directly to another filter as shown here.
app.filter('filterA', function(filterB) {
return function(text) {
return filterB(text);
}
});
Usage shown in the docs here.
Is there an angular JS command that will do HTML escaping on text? I am processing a custom directive and have need to escape some of the output which it generates.
Internally the AngularJS sanitzer uses a encodeEntities function, but does not expose it. I know I could duplicate the function, but it seems like there should be a standard way of doing this.
Use-Case: I have a custom directive which does language localization. This directive uses a key lookup from a data file to find language text. In some cases this text is allowed to contain HTML, and/or the directive produces HTML to improve the resulting visual formatting. In addition this directive takes Angular expressions as parameters and uses them as replacements for tokens in the strings. I need to encode these parameters as they may not be HTML safe.
The directive is called as an attribute, for example i18n-html='welcome_text_html,1+1,user.name'. The directive then formats the string as described and uses element.html to update the DOM node.
This answer is about escaping, not sanitizing HTML. There are two approaches:
As mentioned by #maniekq, if you can work on the DOM, do:
element.text( scope.myValue );
From this answer, you can use this code from mustache.js and e.g. create an angular filter:
angular.module('myModule').filter('escapeHtml', function () {
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
return function(str) {
return String(str).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
});
Sanitizing is one thing, but to display all characters and not "execute" HTML code I have used "text" function to set value.
In your directive, to set value, instead of writing:
element.html( scope.myValue );
write:
element.text( scope.myValue );
This answer is derived from #mb21's. The only thing that is changed is utilizing $sce. So you can use this filter in ng-bind-html, without triggering Error: $sce:unsafe.
angular
.module('yourModule', [
'ngSanitize'
])
.filter('escapeHtml', function ($sce) {
// Modified by Rockallite: Add $sce.trustAsHtml() to mute "Error: $sce:unsafe"
// http://stackoverflow.com/a/32835368/2293304
// http://stackoverflow.com/a/28537958/2293304
// https://github.com/janl/mustache.js/blob/master/mustache.js#L82
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
return function(str) {
return $sce.trustAsHtml(String(str).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
}));
}
});
There are two separate issues with escaping HTML. The first issue is that entities need to be encoded, and the second issue is that the result needs to be trusted so the data can be used as html bindings. Adding the following code to your controller(s) provides a solution for both issues using the $sce service.
CoffeeScript Solution:
MyApp.controller('MyController', ['$scope','$sce',($scope,$sce) ->
###
...
###
$scope.html5Entities = (value) ->
value.replace(/[\u00A0-\u9999<>\&\'\"]/gim, (i) ->
'&#' + i.charCodeAt(0) + ';'
)
$scope.trustAsHtml = (value) ->
$sce.trustAsHtml(value)
###
...
###
])
Javascript Solution:
MyApp.controller('MyController', ['$scope','$sce', function($scope,$sce) {
/* ... */
$scope.html5Entities = function(value) {
return value.replace(/[\u00A0-\u9999<>\&\'\"]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';'
})
};
$scope.trustAsHtml = function(value) {
return $sce.trustAsHtml(value);
};
/* ... */
}]);
The first function html5Entities does the actual entity encoding, while the second function trustAsHtml marks a string as safe to use in Angular for HTML bindings. Both versions require that the $sce service be included in your controller.
Example usage:
<div ng-bind-html="trustAsHtml((html5Entities(product.title) | highlight: $select.search))"></div>
See related issues:
Encode html entities in javascript
AngularJS : Insert HTML into view
You can implement filter like this:
app.filter('escape', escape);
function escape() {
return function (html) {
return angular.element('<pre/>').text(html).html();
};
}
There are two ways to do HTML sanitization in AngularJS. The first is by using the ngBindHtml directive and the second by using the $sanitize service.
function MyCtrl ( $scope, $sanitize ) {
$scope.rawHtml = "<div><script></script></div>";
$scope.sanitizedHmtl = $sanitize( $scope.rawHtml );
}
Then these two are functionally equivalent:
<div ng-bind-html="rawHtml"></div>
<div ng-bind-html-unsafe="sanitizedHtml"></div>
If used in a directive, as in your question, you can simply insert the sanitized HTML:
element.html( scope.sanitizedHtml );
But in most cases when writing directives, you'd have this in a template and use ngBindHtml, as above. But it works for the corner cases.
It's not the straight solution, but if you'd dive into angular-sanitize code, you could find function encodeEntities. It's nice but private. Looking for usages of it you'd go to htmlSanitizeWriter, and then to sanitizeText.
It's still private but used in public filter linky.
Either you can explicitly use linky and hope that no links will be found, or reimplement sanitizeText or encodeEntities int your services.
Use [innerHtml] shorthand tag in a HTML template file you are using in your Angular app.
My example shown below to escape HTML generated by wordpress on post_content that is retrieved from my WP API and therefore the html tags will not display in the browser:
<div [innerHtml]="post.post_content" *ngIf="post && post.post_content"></div>
Hope this helps.
You can use encodeEntities() function in ngSanitize to escape & < > etc.