Projer
Projer

Reputation: 65

Multiple custom filters in AngularJS

I want to put 2 customs filters on a data. Each filter is working perfectly independently, but when I put the 2 on the same data, I have an error message (TypeError: input.replace is not a function), but if I comment this, I have another error message (Error: [$sce:itype] Attempted to trust a non-string value in a content requiring a string: Context: html)

The 2 customs filters are goBold which take no argument, and limitHellip which takes the maximum length of the string as an argument.

thanks a lot, here is the code :

angular.module('appFilters', []).
	filter('goBold', function($sce) {
		return  function (input) {
			input = input.replace(' filter ',' <strong>WORD FILTERED</strong> ');
			return $sce.trustAsHtml( input );
		}
	}).
	filter('limitHellip', function($sce) {
		return  function (input, limit) {
			console.log(limit);
			if( input.length > 100 ) {
				input = input.substring(0,100);
				var index = input.lastIndexOf(" ");
				input = input.substring(0,index) + "&hellip;";
			}
			return $sce.trustAsHtml( input );
		}
	});
<ion-content class="has-subheader">
  <ion-item class="element item item-divider" data-ng-repeat="item in blocInfos" >
    <a href="#/list/{{ item.url }}">
      <img data-ng-src="img/{{ item.imageUrl }}" alt="">
      <h2 class="title">{{ item.title }}</h2>
    </a>
    <p data-ng-bind-html="item.text | limitHellip: 100 | goBold" class="wrap"></p>
  </ion-item>
</ion-content>

Upvotes: 0

Views: 1535

Answers (1)

eroak
eroak

Reputation: 1045

This is because your first filter return an $sce.trusAsHtml() which is an Object and not a string so you can't call the replace() method.

So, you have to change it into a String

Plunkr

Filters

angular.module('appFilters', []).
filter('goBold', function($sce) {
    return  function (input) {

      input = input.toString(); //This line was added

        input = input.replace(' filter ',' <strong>WORD FILTERED</strong> ');
        return $sce.trustAsHtml( input );
    }
}).
filter('limitHellip', function($sce) {
    return  function (input, limit) {
        input = input.toString();      //Maybe you have to add it here too
        console.log(limit);
        if( input.length > limit ) {
            input = input.substring(0,limit);
            var index = input.lastIndexOf(" ");
            input = input.substring(0,index) + "&hellip;";
        }
        return $sce.trustAsHtml( input );
    }
})

Upvotes: 1

Related Questions