gpt4 book ai didi

javascript - Angularjs - 从 JSON 实例化数组

转载 作者:行者123 更新时间:2023-12-02 14:26:49 27 4
gpt4 key购买 nike

我只是尝试从 $http 请求填充数组并在表格中显示结果。在我看来,使用 Firebug 可以正确检索数据。查看图片了解结果。 DOM Results

Firebug Results

    <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 扩展显示以下内容: Batarang

索引“联系人”显示这样正常吗?

最佳答案

在您的 ContactsController 中执行此操作

var self = this; 

现在在 Controller 中使用 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);
});

希望有帮助。

关于javascript - Angularjs - 从 JSON 实例化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38173718/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com