首页 > 解决方案 > ng-repeat 在 angularjs 中的 get 方法中不起作用

问题描述

实际上,我在 angularjs 中编写了代码,在 Web 浏览器中显示检索数据,但 ng-repeat 不起作用。我不知道如何解决它。你可以帮帮我吗?

在角度 js 代码中

$scope.fetchData = function()
{
    $http({
        method: 'GET',
        url: 'fetch_data.php'
    }).then(function (response){
        console.log(response);
        namesData = response.data;
        console.log(namesData );
    },function (error){
        console.log(error);
    });
};
<tr ng-repeat="name in namesData ">
   <td>{{name.first_name}}</td>
   <td>{{name.last_name}}</td>
</tr>

浏览器显示

{mydata: Array(0), namesData: "<[{"first_name":"xvcv","last_name":"sdsd"},{"first_name":"sdvs","last_name":"sdfds"}]"}

标签: angularjshttpangularjs-ng-repeat

解决方案


将您的替换namesData$scope.namesData.

您不能将普通变量绑定到您的模板/视图。你需要使用$scope/$rootScope它。

$scope.namesData = []; //you need to instantiate this first to avoid errors

$scope.fetchData = function()
{
  $http({
    method: 'GET',
    url: 'fetch_data.php'
  }).then(function (response){
    console.log(response);
    $scope.namesData = response.data;
    console.log($scope.namesData );
  },function (error){
    console.log(error);
  });
};

附言

错误:[ngRepeat:dupes]

如果 ngRepeat 表达式中有重复的键,则发生。禁止重复键,因为 AngularJS 使用键将 DOM 节点与项目相关联。

这意味着$scope.namesData有一些重复的值。您可以通过添加来解决"track by $index"

它看起来像这样

ng-repeat="name in namesData track by $index"


推荐阅读