我有一个从服务器检索的对象数组。查询有效,但是当我在html视图中执行ng-repeat
时,它不起作用,它不会显示任何内容。为什么?
这是js代码:
$scope.companyList = [];
$scope.getCompanyList = function() {
$scope.companyList.length = 0;
CompanyListSrv.getCompanyListDetail(function (companyListDetail) {
if (companyListDetail) {
$scope.companyList = companyListDetail;
}
});
};
$scope.getCompanyList();
HTML code:
<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: "text@text.com"
name: "Compant 2"
在控制台中我没有错误,在浏览器的html页面中我有这个:
<!-- ngRepeat: company in companyList -->
答案 0 :(得分:1)
$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
}
});
这里的问题是,angular $ watch机制会检查对象是否已更改,但只记得他的第一个引用。
console.log()
的工作原因是因为您为此函数提供了对象的新引用。
您可以做的是以下内容:
if (companyListDetail) {
for (var i = 0; i< companyListDetail; i++){
$scope.companyList.push(companyListDetail[i]);
}
}
答案 1 :(得分:1)
试试这个会起作用:
您忘记在<table>
中添加Html
代码。
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: "sidhantc@google.com",
name: "Sidhant"
},
{
email: "sid@google.com",
name: "Chopper"
}]
$scope.companyList = companyListDetail;
console.log($scope.companyList);
};
$scope.getCompanyList();
}