0

Looking at Mastering Web Development with AngularJS, I ran this custom filter to trim text, cut out the last 3 characters, and append ... if the input exceeds the LIMIT.

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

However, the length of strs, rather than the individual s, appears to be printing out.

How can I pass each item of the array into my customFilter?

Console

limitToFilter('ABCDEF', 2) A 
input: ["HEY THERE", "me"] input.length 2 limit: 2 
input: ["HEY THERE", "me"] input.length 2 limit: 2 

1 Answer 1

3

You should use the filter on the string, not on the array:

<tr ng-repeat="s in strs">
    <td>{{s | customTrim:2}}</td>
</tr>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.