ECMAScript6 AngularJS 过滤器 [英] ECMAScript6 AngularJS Filter

查看:22
本文介绍了ECMAScript6 AngularJS 过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中使用 ECMAScript6 并尝试创建一个角度过滤器.以下是我的尝试,但是我在控制台中收到以下错误:无法设置未定义的属性PassFilter"

我是 ES6 和 Angular 的新手.由于遗留限制,我不得不以这种方式引导 angular.

myAngularModule = angular.module("MyModule");angular.element(document).ready(function() {var myDiv = $("#myAngularDiv");angular.bootstrap(myDiv, ["MyModule"]);});myAngularModule.filter('PassFilter', APP.filters.PassFilter);/* 过滤器在一个单独的文件中:*/类 PassFilter {构造函数(输入){var split = input.split('');var 结果 = "";for (var i = 0; i < split.length; i++) {结果+=*";}返回结果;}}APP.filters.PassFilter = PassFilter;

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><div id="myAngularDiv"><输入类型=密码"ng-model=密码"><span>{{密码 |PassFilter}}</span>

解决方案

Angular 中的过滤器函数不采用 class 而是采用 过滤器工厂函数.这意味着如果您使用 ES6,您可以使用 lambda 的(箭头函数)来实现过滤器.

myAngularModule.filter('PassFilter', ()=> {返回(输入)=>{var split = input.split('');var 结果 = "";for (var i = 0; i < split.length; i++) {结果+=*";}返回结果;}});

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>

解决方案

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;
   }
});

这篇关于ECMAScript6 AngularJS 过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆