简体   繁体   English

Angular:如何在ng-repeat指令中使用自定义函数?

[英]Angular: How to use custom function inside the ng-repeat directive?

Here is my Template: 这是我的模板:

...
<tr data-ng-dblclick="getCandidateInfo()"
    data-ng-class="{'black-list': candidate.bl}"
    data-ng-repeat="candidate in candidates | orderBy : orderByField : reverseSort">
    <td >{{candidate.fullnameEN}}</td>
    <td>{{candidate.birthDate}}</td>
    <td>{{candidate.phone}}</td>
    <td>{{candidate.email}}</td>
    <td>{{candidate.skype}}</td>
    <td><span ng-show="candidate.bl" class="glyphicon glyphicon-ok"></span></td>
</tr>
...

Question: how to apply custom function convertDate() to {{ candidate.birthDate }} inside the loop? 问题:如何在循环内将自定义函数convertDate()应用于{{候选人。 出生日期 }}?

I would recommend you to either use the built in " date $filter " or if you are doing something VERY unique and the "date $filter " is not good enough for you, then you could create your own $filter , like this: 我建议您使用内置的“ date $filter ”,或者如果您做的事情非常独特并且“ date $filter ”对您来说不够好,那么您可以创建自己的$filter ,如下所示:

app.filter('convertDate', function () {
    return function (date) {
        if (!date) return "";
        var result;
        //your code here    
        return result;
    };
});

And you could use it like this in your template: 您可以在模板中像这样使用它:

{{candidate.birthDate | convertDate}}

You can easily do it... 您可以轻松做到...

define a function in your controller as : 在您的控制器中定义一个函数为:

$scope.convertDate = function(date){
   var convertedDate;
   //convert date here and assign to convertedDate
   return convertedDate;
}

then in view , 然后来看

<td>{{convertDate(candidate.birthDate)}}</td>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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