2016-01-18 80 views
1

This是我正在尋找的。我從一個stackoverflow帖子中得到了這個例子。從第一個字母開始的角度定製搜索

但是,在我的情況下,我需要使用名字的第一個字母進行搜索。

這是json文件。

var userList = { 
    "user":[ 
     { 
     "image": "adam.jpg", 
     "name": "Sanket Jain", 
     "email": "[email protected]", 
     "phone" : "9850987634" 
     }, 
     { 
     "image": "ben.png", 
     "name": "Amar Patil", 
     "email": "[email protected]", 
     "phone" : "9951983334" 
     }, 
     { 
     "image": "max.png", 
     "name": "Prasad Kulkarni", 
     "email": "[email protected]", 
     "phone" : "9253454634" 
     }, 
     { 
     "image": "mike.png", 
     "name": "Tushar Salvi", 
     "email": "[email protected]", 
     "phone" : "9450987634" 
     } 
    ] 
    }; 

回答

0

angular.module('myapp', []).filter('myfilter', function(){ 
return function(input, text){ 
    return input.filter(function(item){ 
     return item.name.startsWith(text); 
    }); 
}; 
}); 

如果您需要不區分大小寫:

angular.module('myapp', []).filter('myfilter', function(){ 
return function(input, text){ 
    return input.filter(function(item){ 
    var lowerStr = (item.name + "").toLowerCase(); 
     return lowerStr.indexOf(text.toLowerCase()) === 0; 
    }); 
}; 
}); 
+0

謝謝@zamarrowski這工作:) – Tushar

0

myfilter功能,而不是此行

return item.startsWith(text); 

如果您需要區分大小寫的嘗試寫這樣一個

return item.name.startsWith(text); 
+0

它不工作,這裏是更新的代碼https://jsfiddle.net/bawsr6as/ – Tushar

+0

我的解決方法是區分大小寫的。我想要不敏感,那麼zamarrowski提供的解決方案將完成這項工作。 –

相關問題