在数组中的对象的Ng重复不起作用

问题描述:

我有一个从服务器检索到的对象数组。查询工作,但是当我在HTML视图中执行ng-repeat时,它不起作用,它不显示任何内容。为什么? 这是js代码:在数组中的对象的Ng重复不起作用

$scope.companyList = []; 

$scope.getCompanyList = function() { 
    $scope.companyList.length = 0; 

    CompanyListSrv.getCompanyListDetail(function (companyListDetail) { 
     if (companyListDetail) { 
      $scope.companyList = companyListDetail; 
     } 
    }); 
}; 

$scope.getCompanyList(); 

HTML代码:

<tr ng-repeat="company in companyList"> 
    <td>{{ company.name }}</td> 
    <td>{{ company.email }}</td> 
    </tr> 

这是companyListDetail阵列(从服务器响应):

companyListDetail: Array[2] 
    0: Object 
    1: Object 
    length: 2 

这是0: Object

email: "[email protected]" 
name: "Compant 2" 

在控制台我没有错误,并在浏览器的HTML页面我有这样的:

<!-- ngRepeat: company in companyList --> 
+0

不能看到obvios错误。请尝试检查下一个: 1.您如何使用异步呼叫?使用$ http?尝试把 $ timeout(function(){$ scope.companyList = companyListDetail;}); 2.将 的console.log(companyListDetail)刚过功能(companyListDetail){调用函数$ scope.getCompanyList(后 – Vitalii

+0

看跌的console.log($ scope.companyList)),并检查是否有可用的数据或不。问题可能是数据(** companyList **)不可用于ng-repeat –

+0

检查'$ scope.companyList = companyListDetail;''console.log($ scope.companyList)',因为它具有相同的对象数组或不。 –

$scope.companyList.length = 0; // This line is good, it empties the array without modifying the reference 

CompanyListSrv.getCompanyListDetail(function (companyListDetail) { 
    if (companyListDetail) { 
     $scope.companyList = companyListDetail; // this line is bad, you assign $scope.companyList to a new reference 
    } 
}); 

这里的问题是,角$钟表机械检查的对象发生了变化,但只记得他的第一次参考。

console.log()工作原因是因为你给这个函数的对象的新引用。

你可以做的是:

if (companyListDetail) { 
    for (var i = 0; i< companyListDetail; i++){ 
     $scope.companyList.push(companyListDetail[i]); 
    } 
} 
+0

它被视为'$ scope's属性。我想简单的'$ scope。$ apply()'会解决它。 –

+0

@vp_arth $ scope。$ apply()可以工作,但会触发应用程序的所有$手表的完整检查。它会降低perfs,并且如果申请已经在进行中,可能会抛出异常。你不应该使用$ apply! –

+0

Deblaton谢谢你,但它不工作......我认为这是因为我在做异步调用,因为我使用的是couchdb – panagulis72

试试这个它会工作:

你忘了在Html添加<table>标签。

HTML:

<div ng-app ng-controller="LoginController"> 
<table> 
<tr ng-repeat="company in companyList"> 
    <td>{{ company.name }}</td> 
    <td>{{ company.email }}</td> 
    </tr> 
</table> 

</div> 

脚本:

function LoginController($scope) { 
    $scope.companyList = []; 

$scope.getCompanyList = function() { 
    $scope.companyList.length = 0; 
    var companyListDetail = [{ 
    email: "[email protected]", 
    name: "Sidhant" 
    }, 
    { 
    email: "[email protected]", 
    name: "Chopper" 
    }] 

      $scope.companyList = companyListDetail; 
      console.log($scope.companyList); 
}; 

$scope.getCompanyList(); 
} 

工作演示:https://jsfiddle.net/Lt7aP/2864/

+0

在我的html中,我正确地写了

,我刚刚选择了一段我的代码!真正的问题是有异步调用 – panagulis72