简体   繁体   中英

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?

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

I think this is what you asked for.. Limiting the name to 10 chars and then adding a "..." to the end of it if it exceeds 10 characters. This is how I would do it. (Also fixed some of your syntax errors).

<option ng-repeat="name in names" value="{{name}}">
    {{name.length <= 10 ? name : name.substring(0, 10) + "..."}}
</option>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM