为每个元素应用自定义角过滤器

Applying Custom Angular Filter per Element

本文关键字:自定义 过滤器 应用 元素      更新时间:2023-09-26

看着精通Web开发与AngularJS,我运行这个自定义过滤器修剪文本,剪掉最后3个字符,并追加...,如果输入超过限制。

app.html

  <div ng-controller="MyCtrl">
       <table>
        <thead>
            <th>Name</th>
        </thead>
        <tbody>
            <tr ng-repeat="s in strs | customTrim:2">
                <td>{{s}}</td>
            </tr>
        </tbody>
    </table>

app.js

var myApp = angular.module('myApp',[]);
myApp.controller("MyCtrl", function ($scope) {
    $scope.strs = ["HEY THERE", "me"];
});
myApp.filter('customTrim', function($filter) {
    var limitToFilter = $filter('limitTo');
    console.log("limitToFilter('ABCDEF', 2)", 
        limitToFilter('ABCDEF', 2));
    return function(input, limit) {
        console.log("input:", input, "input.length", input.length,
         "limit:", limit);
        if(input.length > limit) {
            console.log("returning...");
            console.log(limitToFilter(input, limit-3) + "...");
            return limitToFilter(input, limit-3) + "...";
        }
        return input;
    }
});

然而,输出的似乎是strs的长度,而不是单个的s

我如何将数组的每个项目传递到我的customFilter ?

<<p> 控制台/strong>
limitToFilter('ABCDEF', 2) A 
input: ["HEY THERE", "me"] input.length 2 limit: 2 
input: ["HEY THERE", "me"] input.length 2 limit: 2 

您应该在字符串上使用过滤器,而不是在数组上使用过滤器:

<tr ng-repeat="s in strs">
    <td>{{s | customTrim:2}}</td>
</tr>