I have a small angular filter that insert an (bootstrap) icon in place of a true value. It works but the html is encoded:
var conApp = angular.module('conApp', []);
conApp.filter('trueIcon', function($filter){
return function(booleanValue){
return booleanValue ? '<i class="icon-ok"></i>' : '';
}
});
Do i have to implement another filter to decode the html ? Is there an "angular" way of doing this ?
Filters can be added to expressions by using the pipe character | , followed by a filter.
The “filter” Filter in AngularJS is used to filter the array and object elements and return the filtered items. In other words, this filter selects a subset (a smaller array containing elements that meet the filter criteria) of an array from the original array.
AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.
You need to use ng-bind-html to render html.
<span ng-bind-html="foo | trueIcon"></span>
That said... that's really not what filters are for. Filters are more for scrubbing data being written to a view, rather than generating elements of the view/DOM itself. You'll probably be better off creating a directive for that:
app.directive('trueIcon', function() {
return {
restrict: 'E',
template: '<i ng-class="{\'icon-ok\': value, \'icon-not-okay\': !value}"></i>',
scope: {
value: '='
}
};
});
<true-icon value="foo"></true-icon>
AngularJS is sanitizing results of expression evaluation by default. To display HTML as markup you've got 2 options:
While the above will make your filter work, maybe you should consider turning it into a directive?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With