[英]AngularJS ng-repeat is not looping through array
我正在嘗試使用ng-repeat構建循環,但無法遍歷對象數組。 似乎循環根本沒有運行。
我開始了jsfiddle- http://jsfiddle.net/a2xhzbfm/1/
以下是我正在使用的數據示例( $scope.postData
):
[
{
"Title" : "Test1",
"Content" : "<div class=\"ExternalClass53DA82296DEE49898B93B8E59F9074BD\"><p>This is a test post.</p></div>",
"ImagePath" : "url",
"Text" : "Apple",
"Link" : "http://www.apple.com/",
"Created" : "/Date(1436889599000)/"
}, {
"Title" : "Test2",
"Content" : "<div class=\"ExternalClass53DA82296DEE49898B93B8E59F9074BD\"><p>This is a test post.</p></div>",
"ImagePath" : "url2",
"Text" : "Apple2",
"Link" : "http://www.apple.com/",
"Created" : "/Date(1436889599000)/"
}
]
在JS中,我正在調用一個返回JSON的api,然后將其存儲在$scope.postData
變量中。
var app = angular.module('blogApp',[]);
app.controller('blogController', function($scope){
console.log('Angular is go!');
$scope.postData;
$.ajax({
url: 'someURL',
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
$scope.postData = data.d.results;
console.log($scope.postData);
},
error: function (data) {
console.log(data.responseJSON.error);
}
});
});
到目前為止,這是我對HTML的了解。 一旦可以打印數據,我將添加更多的div。
<body ng-app="blogApp">
<div ng-controller="blogController" class="container">
<div class="row">
<div ng-repeat="post in postData">
<div ng-repeat="(key, val) in post">
{{key}}:{{val}}There has to be something else!!!
</div>
</div>
</div>
</div>
</body>
提前致謝!
這是因為您將jQuery用於Ajax。 Angular不知道您更改了$scope.postData
。 如果您使用Angular自己的Ajax服務$http
,則在對$scope
進行更改后,它將自動處理視圖的更新。 但是由於Angular無法控制jQuery,因此無法檢測到更新。
解決此問題的正確方法是使用$http
,但錯誤的工作方法是在修改$scope.postData
之后立即在成功回調中調用$scope.$apply()
。
嘗試將您的Ajax調用切換到Angular自己的$ http函數,如下所示:
$http.get('someURL', {
headers: {
"Accept": "application/json; odata=verbose"
}
}).success(function(data) {
$scope.postData = data.d.results;
console.log($scope.postData);
});
始終建議使用Angular的內置函數,除非在這些函數不夠用的情況下需要使用外部庫。
1)首先,您需要更新AngularJS的版本
2)您的打印錯誤不是在post而是在postData
核實:
<div ng-repeat="(key, val) in postData">
{{key}}:{{val}}There has to be something else!!!
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.