AngularJS HTML filter on ng options

I am trying to create a custom filter that removes HTML in my select menu. This is what I tried, but it doesn't work.

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

      

This is a display of 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?

+3


source to share


1 answer


You need to change your filter as shown below and your html snippet. You can filter not entire items, but each header.

Below is a 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.com/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>
      

Run code


+7


source







All Articles