AngularJS ng-repeat过滤JSON错误

时间:2016-02-25 11:07:06

标签: angularjs angularjs-ng-repeat

我正在学习AngularJS,当我这样做时,我在Chrome控制台中出错:

            <input ng-model="search" />
            <ul>
                <li ng-repeat="prof in profesores | filter:search">
                    {{prof.nombre}} - {{prof.telefono}}
                </li>
            </ul>

使用此数据“profesores”:

    {
      "profesores": [
          {
            "id": 0,
            "sexo": "hombre",
            "nombre": "Kari",
            "snombre": "Carr",
            "telefono": "(826) 453-3497",
            "celular": "(801) 9175-8136"
          },
          {
            "id": 1,
            "sexo": "mujer",
            "nombre": "Tameka",
            "snombre": "Gamble",
            "telefono": "(824) 438-2499",
            "celular": "(801) 8595-8337"
          }    ]
}

错误是这样的: Error: [filter:notarray]

代码正常工作(在输入中使用字符串过滤项目)但我在控制台中有错误。我做错了什么?

3 个答案:

答案 0 :(得分:1)

这里ng-repeat =“prof in profesores | search” - &gt;错了

ng-repeat =“prof in profesores | filter:search” - &gt;右

var myApp = angular.module('myApp',[]);

myApp.controller('samplecontroller',  function($scope) {
$scope.profesores = [
      {
        "id": 0,
        "sexo": "hombre",
        "nombre": "Kari",
        "snombre": "Carr",
        "telefono": "(826) 453-3497",
        "celular": "(801) 9175-8136"
      },
      {
        "id": 1,
        "sexo": "mujer",
        "nombre": "Tameka",
        "snombre": "Gamble",
        "telefono": "(824) 438-2499",
        "celular": "(801) 8595-8337"
      }
]; 
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html >

<head>
   
</head>

<body ng-app="myApp">

<div ng-controller="samplecontroller">
 <input ng-model="search" />
            <ul>
                <li ng-repeat="prof in profesores |filter: search">
                    {{prof.nombre}} - {{prof.telefono}}
                </li>
            </ul>


</div>
</body>
</html>

答案 1 :(得分:0)

当js加载时,使用像这样的空数组初始化它:

$scope.profesores = []

然后您可以在承诺中再次定义变量:

$http.get('json/profesores.json') .success(function(data){ $scope.profesores = data.profesores; }); 

答案 2 :(得分:0)

在从服务器加载数据之前,您的profesores变量为undefined并将抛出错误。在控制器的开头用空数组初始化它:

$scope.profesores = [];

之后,您可以请求数据并填充数组:

$http.get('json/profesores.json').success(function(response){ 
    $scope.profesores = response.profesores; 
});