使用带过滤数据的AngularJS动态填充选项卡

时间:2014-10-22 10:49:42

标签: json angularjs angular-filters

我有一个json数据

[
   {
      "name": "a",
      "data": "north",
      "value": "10",
      "finished": "50"
   },
   {
      "name": "b",
      "data": "south",
      "value": "100",
      "finished": "10"
   },
   {
      "name": "c",
      "data": "north",
      "value": "20",
      "finished": "50"
   },  
   {
      "name": "a",
      "data": "south",
      "value": "80",
      "finished": "10"
   } 
   ....
]

我想动态添加标签,如果" name"值不同,并在选项卡模板中添加内容。可能有多个具有相同名称的json数组,它们应该在同一个选项卡中一起使用。

我最初做过:

for(var i=0;i<$scope.operation.length;i++) {   
   if($scope.operation[i].name === "a") {
      $scope.tab1 = {
           "title": "Data A" ,"path": "/data"
      };

    }
    if($scope.operation[i].name === "b"){
       $scope.tab2 = {
           "title": "Data B " ,"path": "/datab"
        };

     }
}
and so on ...

如果有多个不同的名称值,则此方法不好。我可以做任何优化来过滤。 对于模板,我使用过滤器显示数据,这又是一个糟糕的方法:

 // custom  filters  - should return data with name value "a" 
$scope.isDCone = function(data,id){
  return data.name === "a";
};

  // custom  filters  - should return data with name value "b"
   $scope.isDCtwo = function(data){
     return data.name === "b";
 };

1 个答案:

答案 0 :(得分:0)

尝试缩小功能

$scope.tabs = $scope.operation.reduce(function(a,b){
    if (a[b.name]){
        a[b.name].push(b);
    } else{
        a[b.name] = [b];
    }
    return a;
}, {});