json - 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");
});
}
});
解决方案
组件控制器应该避免使用 $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
是一个属性。
推荐阅读
- drupal-8 - 使用 drupal 创建自定义主题
- javascript - 如何访问数组对象的元素?
- android - recyclerView 第一次滚动不流畅
- apache-zookeeper - ZooKeeper 超时 - 找不到 myid 文件。视窗服务器 2016
- firebase - Firebase 通知单击 Intent 在背景状态上显示 null - Xamarin.forms Android
- angular - 单击时未显示引导吐司(Angular)
- android - 如何从 Android 应用程序在 Blackberry Access 中打开 URL
- javascript - 如何使用 express.js pg.Pool 调用 Postgres 函数
- angular - 如何使用相同的 url 重新加载一个组件
- typescript - 开玩笑:TypeError:无法读取未定义的属性“foo”