Javascript 如何在ng repeat上获取对象属性的项目计数
我的应用程序使用Bootstrap3和AngularJS。我试图根据ng repeat上的过滤结果计算每个州的农贸市场数量 我的JSON数据如下所示Javascript 如何在ng repeat上获取对象属性的项目计数,javascript,angularjs,twitter-bootstrap,angularjs-scope,angularjs-ng-repeat,Javascript,Angularjs,Twitter Bootstrap,Angularjs Scope,Angularjs Ng Repeat,我的应用程序使用Bootstrap3和AngularJS。我试图根据ng repeat上的过滤结果计算每个州的农贸市场数量 我的JSON数据如下所示 $scope.fmData = [ { "MarketName": "Farm1", "Bakedgoods" :"N", "Cheese":"Y", "Eggs":"N", "latitude": 42.374858, "longitude": -72.519422, "state:": "
$scope.fmData = [
{
"MarketName": "Farm1",
"Bakedgoods" :"N",
"Cheese":"Y",
"Eggs":"N",
"latitude": 42.374858,
"longitude": -72.519422,
"state:": "New York"
},
{
"MarketName": "Farm2",
"Bakedgoods" :"N",
"Cheese":"Y",
"Eggs":"N"
"latitude": 42.5728,
"longitude": -72.1421,
"state:": "Florida"
},
{
"MarketName": "Farm3",
"Bakedgoods" :"Y",
"Cheese":"Y",
"Eggs":"N"
"latitude": 42.318,
"longitude": -71.7757,
"state:": "New York"
}
]
以下是使用自定义过滤器设置ng repeat的方法:
<div ng-repeat="farmer in fmData | myFilter:SearchFood">
以下是我试图实现的一些示例:
默认情况下,如果不检查烘焙食品、奶酪和鸡蛋,我会看到纽约有2个农贸市场,佛罗里达有1个农贸市场
如果我检查鸡蛋,我会发现纽约有0个农贸市场,佛罗里达有0个农贸市场
如果我检查奶酪,我会发现纽约有两个农贸市场,佛罗里达有一个农贸市场
如果我检查一下烘焙食品和奶酪,我会发现纽约有一个农贸市场,佛罗里达有0个农贸市场
任何帮助都将不胜感激 您可以使用$index获取您的
ng repeat
计数编号
$index = $index+1
或者干脆
{{index+1}}
在您的ng repeat
语句/div中
更多信息:
您可以在javascript中使用过滤器。只需将
$filter
注入控制器,然后执行:
var filtered = $filter('myFilter')($scope.fmData, $scope.SearchFood);
这将为您提供过滤后的数组,您可以在其中循环:
$scope.statesCount = {};
filtered.forEach(function(item){
// if item.state is not in our object yet, create it with value of 1
if(typeof $scope.statesCount[item.state] === "undefined")
$scope.statesCount[item.state] = 1;
// if it is, increment its count
else
$scope.statesCount[item.state]++;
}
然后:
等等。感谢AngularHarsh的建议,但我正在尝试计算对象属性的值在ng repeat上出现的次数。比如,我如何计算在ng repeat的“州”中有多少纽约和佛罗里达州。如果我做fmData.length,我可以得到农贸市场的总数(3)。但是,我想更具体地说,2个农贸市场来自纽约,1个来自佛罗里达州。您应该为此创建plunker/JSFIDLE。卡米尔克能够帮助我摆脱困境。谢谢你!当我有机会回答未来的问题时,我将尝试学习如何使用plunker/JSFIDLE:)
var filtered = $filter('myFilter')($scope.fmData, $scope.SearchFood);
$scope.statesCount = {};
filtered.forEach(function(item){
// if item.state is not in our object yet, create it with value of 1
if(typeof $scope.statesCount[item.state] === "undefined")
$scope.statesCount[item.state] = 1;
// if it is, increment its count
else
$scope.statesCount[item.state]++;
}
$scope.statesCount['New York'] // equals number of farmers markets in New York
$scope.statesCount['Florida'] // equals number of farmers markets in Florida