AngularJS - 自定义过滤器不起作用

问题描述 投票:1回答:1

我想找到名字,从给定的字母开始,即使用angular的自定义过滤器'm'。在这里,我应该在解决方案中获得2个条目,但我的视图部分仅显示无序列表的两个项目符号,而不显示以“m”开头的名称。

这是我的过滤器:

 arg.filter("startwith",function()
 {
    return function(input,option)
    {
       var op = [];//var s="";
       for(var i=0;i<input.length;i++)
       {
          if(input[i].sname.charAt(0) == option)
             op.push(input[i].sname);
       }
      // $scope.op;
      // s=op.toString();
       return op;
    }
 });

这是控制器:

 $scope.stud = [
                  {sid:1,sname:'john',gender:1,type:"fulltime"},
                  {sid:2,sname:'ashish',gender:1,type:"fulltime"},
                  {sid:3,sname:'naina',gender:2,type:"parttime"},
                  {sid:4,sname:'mitesh',gender:3,type:"fulltime"},
                  {sid:5,sname:'mithila',gender:2,type:"parttime"}
                ]

这是观点:

<h3> Names Start with M</h3>
<ul>
   <li ng-repeat="s in stud | startwith : 'm'">
       {{stud.sname}} 
   </li>
 </ul> 
angularjs
1个回答
0
投票

这是因为在您的自定义过滤器中,您不返回对象而是返回字符串,因此以下内容将返回空,因为您的字符串不具有sname属性

<ul>
   <li ng-repeat="s in stud | startwith : 'm'">
       {{s.sname}} 
   </li>
</ul> 

将{{s.sname}}行更改为{{s}}会为您提供结果。

<ul>
   <li ng-repeat="s in stud | startwith : 'm'">
       {{s}} 
   </li>
</ul> 

Demo

© www.soinside.com 2019 - 2024. All rights reserved.