user1809790 user1809790 - 5 months ago 35
Javascript Question

ECMAScript6 AngularJS Filter

I am using ECMAScript6 in a project and am trying to create an Angular Filter. Below is my attempt, however I am getting the following error in the console:
Cannot set property 'PassFilter' of undefined

I am new to both ES6 and Angular. I had to bootstrap angular that way due to legacy limitations.



myAngularModule = angular.module("MyModule");

angular.element(document).ready(function() {
var myDiv = $("#myAngularDiv");
angular.bootstrap(myDiv, ["MyModule"]);
});

myAngularModule.filter('PassFilter', APP.filters.PassFilter);



/* Filter is in a separate file: */
class PassFilter {

constructor(input) {

var split = input.split('');
var result = "";
for (var i = 0; i < split.length; i++) {
result += "*";
}
return result;

}
}

APP.filters.PassFilter = PassFilter;

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div id="myAngularDiv">
<input type="password" ng-model="password">
<span>{{password | PassFilter}}</span>
</div>




Answer

Filter function in Angular does not take a class but a filter factory function. This implies if you are using ES6 you can use lambda's (arrow function) to implement the filter.

myAngularModule.filter('PassFilter', ()=> {
   return (input)=> { 
      var split = input.split('');
      var result = "";
      for (var i = 0; i < split.length; i++) {
       result += "*";
      }
      return result;
   }
});