在AngularJs中获取JSON文件的大小返回不正确的值

时间:2017-10-27 17:29:00

标签: javascript html angularjs json

您好我目前正在学习AngularJS和JS,并且我试图返回JSON文件中的条目数。 JSON文件看起来像这样:

{
  "title": "Watching the Wheels",
  "artist": "John Lennon",
  "year": "1981",
},
{
  "title": "Way Over Yonder in the Minor Key",
  "artist": "Billy Bragg & Wilco",
  "year": "1998",
},
{
  "title": "We Are Never Ever Getting Back Together",
  "artist": "Taylor Swift",
  "year": "2012",
},
{
  "title": "We're Going To Be Friends",
  "artist": "The White Stripes",
  "year": "2001",
}

我将其显示在页面上,并且必须能够进行即时搜索(可行)。我只想要它返回条目数。它目前正在返回19,并且JSON文件中有大约200个条目。

我的html文件看起来像这样:

<!DOCTYPE html>
<html  ng-app ="ngApp">
<head>
<title>First AngularJS Application</title>
<script src= "/Scripts/angular.js"></script>
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<!--<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>-->
<title>Angular - INDEX</title>
</head>

<body ng-controller="myController">
Artist: <input type="text" ng-model="artist"><br /> # of songs: <span>{{count}}</span>
Order by:
<a href="" ng-click="predicate = 'artist'">Artists</a>
<a href="" ng-click="predicate = 'year'">Year</a>
<ul>
    <li ng-repeat="artist in artists | filter: artist | orderBy: predicate" >
        {{ artist.artist }} | {{ artist.title }} | {{artist.year}}
    </li>
</ul>
<script>
var ngcontr = angular.module('ngApp', []);
    ngcontr.controller('myController', function ($scope, $http) {
        $http.get('data.json')
            .then(function (res) {
                $scope.artists = res.data;
            });
        $scope.predicate = 'year';
        $scope.count = Object.keys(ngcontr).length;
    });
    </script>
</body>
</html>

感谢任何帮助。还可以在更新搜索时更新计数?

1 个答案:

答案 0 :(得分:1)

你需要检查数组的长度而不是对象键,

 $http.get('data.json')
 .then(function (res) {
    $scope.artists = res.data;
    $scope.count = $scope.artists.length;
});