2016-06-10 38 views
0

我有一個從服務器檢索到的對象數組。查詢工作,但是當我在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)',因爲它具有相同的對象數組或不。 –

回答

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 
    } 
}); 

這裏的問題是,角$鐘錶機械檢查的對象發生了變化,但只記得他的第一次參考。

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

1

試試這個它會工作:

你忘了在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