Angularjs - 来自JSON

时间:2016-07-03 19:43:00

标签: javascript arrays angularjs json

我只是尝试从$ 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

将“联系人”这样的索引显示出来是否正常?

2 个答案:

答案 0 :(得分:1)

在您的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);
});

希望有所帮助。

答案 1 :(得分:1)

<div>
  <img src="http://www.fillmurray.com/g/200/300" alt="">
</div>

<h3> Original Image </h3>

<img src="http://www.fillmurray.com/g/200/300" alt="">

在这种情况下,this.contactList = angular.fromJson(response.data); 引用this调用的匿名回调函数的函数原型。在许多回调等中使用单词then()时要小心Javascript。声明一个变量,并分配所需的函数原型,然后引用该变量,而不是保留的,不断变化的this关键字。