[英]Angularjs - Instantiate array from JSON
我只是想從$ http請求中填充一個數組,並在表中顯示結果。 在我看來,使用Firebug可以正確檢索數據。 查看結果圖片。
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('ContactsController', function ($scope, $http)
{ var self = this; //added after initial post.
this.contactList = [];
this.InitiateContactList = function(arrayContacts) //this.InitiateContactList doesn't work?
{ for(i = 0; i < arrayContacts.length; i++)
this.contactList.push(arrayContacts[i]);
};
$http({
method: 'GET',
url: 'someurl', //pseudoCode
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response)
{ if(angular.isArray(response.data))
{ //this.contactList = response.data; //is this working properly?
self.contactList = angular.fromJson(response.data);
//this.InitiateContactList(response.data);
}
}, function errorCallback(response) {
});
});
app.controller('ActionsController', function ($scope, $http)
{
});
</script>
</head>
<body ng-controller="ActionsController as ActCtrl">
<div ng-controller="ContactsController as ContactsCtrl">
<table
<tr><th Email</th>
<th>Name</th>
<th>Frequency</th></tr>
</table>
<div ng-repeat="Contact in ContactsCtrl.contactList">
<table >
<tr><td>{{Contact.Email}}</td><td>test name</td><td>{{Contact.Frequency}}</td></tr>
</table>
</div>
</div>
</body>
</html>
this.contactList = angular.fromJson(response.data); 似乎正在工作。 DOM數組已按預期填充,但是ng-repeat似乎不起作用。 在其他情況下,我已經多次執行了此過程,並且按預期工作。 我想念什么?
更新:Chrome中的Batarang擴展程序顯示以下內容:
像這樣顯示索引“聯系人”是否正常?
在您的ContactsController中,執行此操作
var self = this;
現在在控制器中使用self
代替所有this
:
$http({
method: 'GET',
url: 'someurl', //pseudoCode
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
self.contactList = angular.fromJson(response.data);
});
希望能有所幫助。
this.contactList = angular.fromJson(response.data);
在這種情況下, this
是指then()
調用中的匿名回調函數的函數原型。 在許多回調等中使用單詞this
時,請小心使用Javascript。 聲明一個變量,並分配所需的函數原型,然后引用該變量,而不是保留的,不斷更改this
關鍵字的變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.