ng-repeat中的Angular Js对象过滤器

时间:2016-03-10 13:35:25

标签: javascript angularjs json

如何根据对象值(如1或2或3

)进行过滤

我正在尝试过滤看起来类似于名称对象

的json

这是我的代码我试图应用过滤器,但它无法正常工作

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="namesCtrl">

<ul>
  <li ng-repeat="x in names ">
    {{ x.name }}
  </li>
</ul>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = {
  "1": {
       "name": "some"
  },
  "2": {
       "name": "values"
  },
  "3": {
        "name": "are"
  },
  "4": {
       "name": "there"
  },
  "5": {
        "name": "here"
  }
}
});
</script>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

我认为你不能过滤属性名称。我假设这些属性名称是您想要过滤的某种ID。那么你的数据结构应该反映出来并且如下所示:

$scope.names = [
    { id: "1", name: "some" },
    { id: "2", name: "values" },
    { id: "3", name: "are" },
    { id: "4", name: "there" },
    { id: "5", name: "here" }
]

然后你可以像这样过滤:

<ul>
  <li ng-repeat="x in names | filter: { id: searchId } >
    {{ x.name }}
  </li>
</ul>

searchId替换为包含您要查找的ID的特定范围变量。

答案 1 :(得分:0)

filter和orderBy不适用于对象属性,只适用于数组。话虽这么说,我想我找到了一个你想要的解决方案:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="namesCtrl">

<input type="text" ng-model="searchText"/>
<ul ng-init="nameArray=objArray(names)">
  <li ng-repeat="x in nameArray | filter:searchText">
    {{x.value.name}}
  </li>
</ul>

</div>

<script>

angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.searchText='';
    $scope.names = {
  "1": {
       "name": "some"
  },
  "2": {
       "name": "values"
  },
  "3": {
        "name": "are"
  },
  "4": {
       "name": "there"
  },
  "5": {
        "name": "here"
  }
    };
$scope.objArray=function (obj) {
    var result=[];
    for (var key in obj) {
        result.push({
            key: key,
            value: obj[key]
        });
    }
    return result;
}


});
</script>

</body>
</html>