Search code examples
javascriptangularjsangularjs-ng-repeatangular-filters

ng-repeat filter with condition angular js


This is my code :

 <option ng-repeat="name in names" value="{{names.name}">
    {{names.name | limitTo:10 }}
 </option>

How can I add a condition:

if( names.name.length > 10) { 
     //add ... point after name displayed 
}

to get result <option value="Alexander Bradley">Alexander ... </option>

Any ideas?


Solution

  • You can create your own filter that does this and include the length parameter if you like.

    .filter("ellipses", function () {
        return function (item) {
            if (item.length > 10) {
                return item.substring(0, 10) + " ..."
            }
            return item;
        };
    });
    
    <option ng-repeat="name in names" value="{{names.name}">
        {{names.name | ellipses }}
    </option>
    

    You can include the length argument as well and even use limitTo itself:

    .filter("ellipses", ["$filter", function ($filter) {
        return function  (item, limit) {
            if (item.length > limit) {
                return $filter("limitTo")(item, limit) + " ...";
            }
            return item;
        };
    }]);