如何在angularjs中显示JSON列表数据

时间:2014-03-05 09:10:27

标签: angularjs rest angularjs-scope angularjs-ng-repeat angularjs-service

我是Angularjs的新手并且无法显示数据。即Json数组

这是我的休息服务电话的结果:

{
    "users": [{
        "id": 1,
        "firstname": "Naveen",
        "lastname": "Dutt",
        "email": "navee23ndutt12.vyas@gmail.com",
        "telephone": "7829418456445355"
    }]
}

这是我的控制者:

app.controller('MyCtrl2', ['$scope', 'NFactory', function ($scope, NFactory) {
    alert("here??");
    $scope.bla = NFactory.query;
    alert("here??" + $scope.bla);

    NFactory.get({}, function (nFactory) {
        $scope.allposts = nFactory.firstname;
    })
}]);

这是我的HTML:

<div>
    <ul >
        <li ng-repeat="user in bla"> {{ user.firstname }} </li>
    </ul>
</div>

但它在UI上没有显示任何内容。可能是什么问题?请建议。

4 个答案:

答案 0 :(得分:2)

这是因为您调用异步任务。我会以承诺包装结果。

以下是异步调用的基本模拟:

演示 Fiddle

var app = angular.module('myModule', ['ngResource']);

app.controller('fessCntrl', function ($scope, Data) {

        Data.query()
            .then(function (result) {
                console.log(result);
            $scope.bla = result.users;
        }, function (result) {
            alert("Error: No data returned");
        });


});

app.$inject = ['$scope', 'Data'];

app.factory('Data', ['$resource', '$q', function ($resource, $q) {
    var data = {
        "users": [{
            "id": 1,
            "firstname": "Naveen",
            "lastname": "Dutt",
            "email": "navee23ndutt12.vyas@gmail.com",
            "telephone": "7829418456445355"
        }]
    };

//Actually we can use $resource
//var data = $resource('localhost/shfofx/PHP/Rest/alertLossDetails.php', 
//       {},
//      { query: {method:'GET', params:{}}}
//               );
    var factory = {

        query: function (selectedSubject) {
            var deferred = $q.defer();          
            deferred.resolve(data);           
            return deferred.promise;
        }

    }
    return factory;
}]);

答案 1 :(得分:1)

如果您的情况为$scope.bla

{"users":[{"id":1,"firstname":"Naveen","lastname":"Dutt","email":"navee23ndutt12.vyas@gmail.com","telephone":"7829418456445355"}]

然后你的模板应如下所示:

<ul >
    <li ng-repeat="user in bla.users"> {{ user.firstname }} </li>
</ul>

另一种方法是更改​​Controller内的代码,如下所示:

$scope.bla = NFactory.query.users;

并保留模板。

答案 2 :(得分:1)

如果NFactory.query是字符串,则需要先将其解析为JSON。

$scope.bla=JSON.parse(NFactory.query);

然后

<ul >
    <li ng-repeat="user in bla.users"> {{ user.firstname }} </li>
</ul>

希望这会有所帮助......

答案 3 :(得分:0)

不应该是方法调用:NFactory.query()

请出示NFactory来源。

更新:尝试从服务器响应数组:

[{
    "id": 1,
    "firstname": "Naveen",
    "lastname": "Dutt",
    "email": "navee23ndutt12.vyas@gmail.com",
    "telephone": "7829418456445355"
}]

并使用NFactory.query()