首页 > 解决方案 > AngularJS 获取 JSON 文件但它不会显示

问题描述

我现在在一个小型 AngularJS(1.6.6) 网站上工作,我正在从我的 projects.js 组件(不是我的主/索引 js 文件)中调用一个(本地)JSON 文件。检索数据并在控制台中,当我 console.log($scope.projectItems) 时显示 JSON 数组。但是,当我尝试提取该数据并使用 ng-repeat 将其显示给最终用户时,没有显示任何内容,并且控制台中也没有错误。

谁能给我一个关于我做错了什么的建议?
谢谢你。


[{
        "Name": "Home 1",
        "Text": "This is the Image of home 1"
    },
    {
        "Name": "Home 2",
        "Text": "This is the Image of home 2"
    }
]
<ul class="Projects_List">
    <li class="Project_Item" ng-repeat="Item in $ctrl.projectItems"> 
        {{Item.Name}}
      </li>
</ul>

angular.
module('App').
component('projects', {
    templateUrl: "projects.html",
    controller: function ProjectController($scope, $http) {

        $http({
            method: 'GET',
            url: 'HomeProjects.json'
        }).then(function(data) {
            $scope.projectItems = data;
            console.log($scope.projectItems);
            console.log("This is working");

        }, function(error) {
            console.log("There is an error");
        });

    }
});

标签: jsonangularjs

解决方案


组件控制器应该避免使用 $scope。它使迁移到 Angular 2+ 变得更加困难。

而是使用this上下文:

app.component('projects', {
    templateUrl: "projects.html",
    controller: function ProjectController( ̶$̶s̶c̶o̶p̶e̶ , $http) {
        var $ctrl = this;
        $http({
            method: 'GET',
            url: 'HomeProjects.json'
        ̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶(̶d̶a̶t̶a̶)̶ ̶{̶
        }).then(function(response) {
            ̶$̶s̶c̶o̶p̶e̶.̶p̶r̶o̶j̶e̶c̶t̶I̶t̶e̶m̶s̶ ̶=̶ ̶d̶a̶t̶a̶;̶
            $ctrl.projectItems = response.data;
            console.log($ctrl.projectItems);
            console.log("This is working");

        }, function(error) {
            console.log("There is an error");
            throw error;
        });

    }
});

$http 服务承诺也返回一个response对象,该对象data是一个属性。


推荐阅读