如何在anguarljs中使用具有某些条件的独特过滤器

时间:2016-10-12 10:46:19

标签: javascript angularjs

我的记录很少,我想对特定记录使用唯一过滤器,例如只显示"SubProjectId": "1"一次。我不知道如何在条件下使用这个过滤器。这是我的数据

var projects = [
 {
"DisciplineId": "240",
"DisciplineName": "General",
"SubProjectId": "1"
},
{
 "DisciplineId": "244",
"DisciplineName": "General 2",
"SubProjectId": "1"
},
{
"DisciplineId": "140",
"DisciplineName": "General etc",
"SubProjectId": "2"
},
{
"DisciplineId": "10",
"DisciplineName": "dsdsd",
"SubProjectId": "12"
},
{
 "DisciplineId": "340",
"DisciplineName": "dffd",
"SubProjectId": "2"
  } 
  ]

在Html中:

<ul>
  <li ng-repeat="project in projects |
  unique: 'SubProjectId' ">{{project.SubProjectId}}</li>
</ul>

我想要的结果数据是这样的:

$scope.projects = [
{
"DisciplineId": "240",
"DisciplineName": "General",
"SubProjectId": "1"
 }
{
"DisciplineId": "140",
"DisciplineName": "General etc",
"SubProjectId": "2"
},
{
"DisciplineId": "10",
"DisciplineName": "dsdsd",
"SubProjectId": "12"
},
{
"DisciplineId": "340",
"DisciplineName": "dffd",
"SubProjectId": "2"
  } 
  ];

3 个答案:

答案 0 :(得分:0)

您只需使用ng-showng-if

即可
    <ul>
      <li ng-repeat="project in projects ng-if="project.SubProjectId==1">
         {{project.SubProjectId}}
      </li>
    </ul>

答案 1 :(得分:0)

你也可以使用过滤器,

<ul>
  <li ng-repeat="project in projects | filter: myFilter">
     {{project.SubProjectId}}
  </li>
</ul>

$scope.myFilter = function (item) { 
    return item. SubProjectId == '1';
};

答案 2 :(得分:0)

您不需要filter。只需添加一个函数,该函数将返回仅包含SubProjectId: "1"的第一条记录的已过滤列表。休息所有记录都是一样的

    $scope.getProjects = function()
  {
    var list = [];
    var forone = false;
    console.log
    for(var i=0;i<$scope.projects.length;i++)
    {
        if($scope.projects[i].SubProjectId == "1")
      {
        if(!forone)
        {
            list.push($scope.projects[i]);
          forone = true;
        }

      }
      else
      {
        list.push($scope.projects[i]);
      }

    }
    return list;
  };

HTML

<ul>
    <li ng-repeat="project in getProjects()">{{project}}</li>
  </ul>

<强> FULL EXAMPLE