Reputation: 2169
I have an Array of Objects retrieved from server. The Query works, but when I do the ng-repeat
in the html view, it doesn't work, it doesn't show anything. Why?
This is the js code:
$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>
This is the companyListDetail Array (response from server):
companyListDetail: Array[2]
0: Object
1: Object
length: 2
This is the 0: Object
:
email: "[email protected]"
name: "Compant 2"
In console I have no error, and in html page of browser I have this:
<!-- ngRepeat: company in companyList -->
Upvotes: 0
Views: 642
Reputation: 11
Try this it will work :
You forgot to add <table>
tag in 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>
Script :
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();
}
Working demo : https://jsfiddle.net/Lt7aP/2864/
Upvotes: 1
Reputation: 11397
$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
}
});
The issue here, is that angular $watch mechanism checks if the object has changed but has only remembered his first reference.
The reason why console.log()
works is because you give this function the new reference of your object.
what you can do is the following :
if (companyListDetail) {
for (var i = 0; i< companyListDetail; i++){
$scope.companyList.push(companyListDetail[i]);
}
}
Upvotes: 1