【问题标题】:AngularJS gets JSON file but it won't displayAngularJS 获取 JSON 文件但它不会显示
【发布时间】:2019-06-27 15:47:56
【问题描述】:

我现在在一个小型 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");
        });

    }
});

【问题讨论】:

    标签: json angularjs


    【解决方案1】:

    组件控制器应该避免使用 $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 是一个属性。

    【讨论】:

    • 谢谢,现在可以使用了。但是,如果 $ct​​rl 是控制器,我不明白为什么要将它存储在 $ctrl 中?你能解释一下吗?我所做的是将其存储在另一个变量调用 vm 中并且仍然有效。谢谢。
    • 在控制器中,可以将this分配给任何标识符。我使用了$ctrl,因为它与控制器绑定到范围的方式相匹配。有些人使用vm。任何标识符都可以使用。
    【解决方案2】:

    在模板中,您尝试访问控制器上的项目,但它们在范围内。

    试试改一下

    <li class="Project_Item" ng-repeat="Item in $ctrl.projectItems">
    

    到这里

    <li class="Project_Item" ng-repeat="Item in projectItems">
    

    【讨论】:

    • 组件控制器应该避免使用$scope。它使迁移到 Angular 2+ 变得更加困难。
    猜你喜欢
    • 2017-06-05
    • 2020-06-05
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 2021-10-09
    • 2019-03-14
    相关资源
    最近更新 更多