Angular JSON - 使用'track by'表达式

时间:2015-01-05 04:55:02

标签: javascript php mysql json angularjs

我正在使用angular + Php + MySql进行CRUD,我遇到了问题。 我在数据库中有一些数据,想在列表页面上显示它。

为了达到这个目的,我在Angular中进行了ajax调用,并将响应放在Scope Variable中。如果我打印响应它显示我低于响应但不能用HTML显示它。我遇到了一个问题,即: -

错误:[ngRepeat:dupes]不允许在转发器中重复。使用'跟踪'表达式以指定唯一键。中继器:船员,重复键:字符串:",重复值:" \""

以下是Angular和HTML代码: -

.controller('wrapperController', ['$scope','$rootScope','$http', function(scope,rootScope,http){

    http.post("server/viewRecords.php")
    .success(function(response){
        console.log(response);
        scope.crew = response;

    });
}])

<tr ng-repeat="person in crew">
            <td>{{person.name}}</td>
            <td>{{person.desc}}</td>
            <td> <a href="#/edit/{{$index}}">Edit</a> </td>
            <td> <a href="#/delete/{{$index}}" data-ng-click="deleteRecord($index)">Delete</a> </td>
        </tr>

请说明我收到此错误的原因?

谢谢!

1 个答案:

答案 0 :(得分:5)

AngularJS不允许在ng-repeat指令中使用重复项。因此,您可以将track by $index添加到ng-repeat中,如下所示:

<tr ng-repeat="person in crew track by $index">
            <td>{{person.name}}</td>
            <td>{{person.desc}}</td>
            <td> <a href="#/edit/{{$index}}">Edit</a> </td>
            <td> <a href="#/delete/{{$index}}" data-ng-click="deleteRecord($index)">Delete</a> </td>
</tr>

Track by $index告诉angular使用$index(自动递增)作为键而不是数组中的每个单独元素。所以,它不再重复了。