angularjs newline filter with no other html

后端 未结 7 1092
北恋
北恋 2020-12-07 14:14

I\'m trying to convert newline characters (\\n) to html br\'s.
As per this discussion in the Google Group, here\'s what I\'ve got:



        
7条回答
  •  星月不相逢
    2020-12-07 14:53

    I'm not aware if Angular has a service to strip html, but it seems you need to remove html before passing your newlines custom filter. The way I would do it is through a custom no-html directive, which would be passed a scope property and the name of a filter to apply after removing the html

    Here's the implementation

    app.directive('noHtml', function($filter){
      return function(scope, element, attrs){
        var html = scope[attrs.noHtml];
        var text = angular.element("
    ").html(html).text(); // post filter var filter = attrs.postFilter; var result = $filter(filter)(text); // apending html element.html(result); }; });

    The important bit is the text variable. Here I create an intermediate DOM element and append it the HTML using the html method and then retrieve only the text with the text method. Both methods are provided by Angular's lite version of jQuery.

    The following part is applying the newline filter, which is done using the $filter service.

    Check the plunker here: http://plnkr.co/edit/SEtHH5eUgFEtC92Czq7T?p=preview

提交回复
热议问题