最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS strip HTML filter on ng-options - Stack Overflow

programmeradmin4浏览0评论

I'm trying to create a custom filter that strips HTML on my select menu. This is what I've tried, but it doesn't work.

            <select
                ng-options="item.name for item in list | htmlToPlaintext">
                <option value="">Select</option>
            </select>

It's rendering empty values.

            app.filter('htmlToPlaintext',
            function () {
                 return function (items) {
                      var filtered = [];
                      angular.forEach(items, function (item) {
                            var stripped = String(item).replace(/<[^>]+>/gm, '');
                            filtered.push(stripped);
                      });
                      return filtered;        
                 }
            });

Has anyone applied this type of filter to ng-options in Angular?

I'm trying to create a custom filter that strips HTML on my select menu. This is what I've tried, but it doesn't work.

            <select
                ng-options="item.name for item in list | htmlToPlaintext">
                <option value="">Select</option>
            </select>

It's rendering empty values.

            app.filter('htmlToPlaintext',
            function () {
                 return function (items) {
                      var filtered = [];
                      angular.forEach(items, function (item) {
                            var stripped = String(item).replace(/<[^>]+>/gm, '');
                            filtered.push(stripped);
                      });
                      return filtered;        
                 }
            });

Has anyone applied this type of filter to ng-options in Angular?

Share Improve this question asked Sep 19, 2014 at 18:57 mrtonybmrtonyb 6152 gold badges7 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Your need to modify your filter like shown below and your html snippet too. You can apply the filter not whole items but each title.

Below is the demo:

angular.module('selectFilters', ['filters']);
angular.module('filters', []).filter('htmlToPlaintext', function() {
    return function(text) {
      return String(text).replace(/<[^>]+>/gm, '');
    }
  });

function ItemCtrl($scope, $filter){
    $scope.Items = [
        {ID: '000001', Title: '<b>Chicago</b>'},
        {ID: '000002', Title: '<b><i>New York</i></b>'},
        {ID: '000003', Title: '<div><p>Washington</p></div>'}
    ];    
}
<script src="https://ajax.googleapis./ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="selectFilters">
    <div ng-controller="ItemCtrl">
        <div>
            <select ng-model="item" ng-options="(item.Title | htmlToPlaintext) for item in Items"></select>
        </div>
    </div>
</div>

发布评论

评论列表(0)

  1. 暂无评论