【问题标题】:filtering $http json data with angular使用角度过滤 $http json 数据
【发布时间】:2017-10-23 10:26:38
【问题描述】:

我已经在这里阅读了许多问题,但是我并没有点击并理解我遇到的这个问题。

js代码:

    app.controller('example_ctrl',['$scope','$http', function($scope, 
    $http){
    $http.get('api_call_here').then(function successCallBack(response){
    $scope.response = response;
    });

api的json格式:

    {
      "categoryOne": {
        "1": {
          "title": "someData1",
          "description": "This is number One"
        },
        "2": {
          "title": "moreData1",
          "description": "I am not a number, I'm a free man!"
        }
      }
    }

现在因为这没有在数组中返回,所以每当我尝试过滤它时都会出错。举个例子:

    <div ng-repeat="(category, object) in response.data">
       <div ng-repeat="item in object">
         <p>{{item.title}}</p>
       </div>
    </div>

现在,如果我尝试将 ng-model 放在搜索输入上,并使用 |filter:ng-model 名称将其绑定到 ng-repeat,我会收到错误消息。

我基本上想要做的是,当您在搜索字段中输入文本时,让它只返回包含该文本的标题/描述。

【问题讨论】:

  • 您是否检查过您的 api 的输出标头是否设置为 application/json?如果它只是一个字符串,它不会返回真正的 json
  • console.log 结果返回一个对象。
  • 您必须将项目映射到数组,因为过滤器不适用于对象

标签: javascript angularjs json


【解决方案1】:

您可以将每个类别中的对象列表转换为数组:

app.controller('example_ctrl',['$scope','$http', function($scope, $http){
    $http.get('api_call_here').then(function(response) {    
        Object.keys(response.data).forEach(function(category) {
        response.data[category] = Object.values(response.data[category]); // Transfom list of objects in each category to array
    });
    console.log("transformed: ", response);
    $scope.response = response;	
});

【讨论】:

  • 请注意,您也可以在控制器中进行过滤,而不是在视图中增加开销
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
相关资源
最近更新 更多