在导入的JSON对象AngularJS中获取一个数组
Grab an array within imported JSON object - AngularJS
我正在构建一个快速的Angular应用程序,该应用程序使用服务从URL获取JSON。
JSON结构如下:
{news:[{title:"title",description:'decription'},
{title:"title",description:'decription'},
{title:"title",description:'decription'}
]};
我需要的只是新闻对象中的数组。
我导入JSON的代码如下:
app.factory('getNews', ['$http', function($http) {
return $http.get('URL')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
然后,为了将数据添加到控制器中的$scope对象,我这样做:
app.controller('MainController', ['$scope','getNews', function($scope, getNews) {
getNews.success(function(data)) {
$scope.newsInfo = data.news;
});
});
但它不起作用。当我加载html页面时,只有白色。我的想法是,这是因为它没有获取JSON中的数组,并使用这些数据来填充我设置的HTML指令。
newsInfo.js:
app.directive('newsInfo',function(){
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl:'newsInfo.html'
};
});
newsInfo.html:
<h2>{{ info.title }}</h2>
<p>{{ info.published }}</p>
我的HTML文档是:
<head>
<title></title>
<!--src for AngularJS library-->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
</head>
<body ng-app="THE APP NAME"> <!--insert ng app here-->
<div ng-controller="MainController"> <!--insert ng controller here-->
<div ng-repeat="news in newsInfo"><!--insert ng repeat here-->
<!-- directive goes here-->
<newsInfo info="news"></newsInfo>
</div>
</div>
<!-- Modules -->
<script src="app.js"></script>
<!-- Controllers -->
<script src="MainController.js"></script>
<!-- Services -->
<script src="getNews.js"></script>
<!-- Directives -->
<script src="newsInfo.js"></script>
</body>
想法?
更改
<newsInfo info="news"></newsInfo>
至
<news-info info="news"></news-info>
示例:https://jsfiddle.net/bhv0zvhw/3/
您尚未指定控制器。
<div ng-controller="MainController"> <!--insert ng controller here-->
<div ng-repeat="news in newsInfo"><!--insert ng repeat here-->
<!-- directive goes here-->
<newsInfo info="news"></newsInfo>
</div>
</div>
$scope.getNews = function(){
return $http.get('URL').success(function(data) {
return data.news;
})
};
^这一点,只需更改它,使成功函数只返回消息!
当我回答自己的问题时,我应该指出每个人的答案都是正确的。该代码有多个错误,但通过以下操作修复了最终错误:
显然,我不得不将newsInfo.html文档上传到S3存储桶中,并将该URL用作“Cross origin requests are only supported for HTTP.”
,但随后Angular用错误"$sce:insecurl Processing of a Resource from Untrusted Source Blocked"
阻止了该外部源。
因此,由于html模板非常简单,我只需在.js指令中直接输入模板,就可以解决这个问题了!感谢大家的帮助!
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 根据id将json数组组合为一个json数组
- JavaScript数组包含一个值
- 对一个对象使用reduce可以返回一个没有't在数组中包含目标字母
- jQuery$.inArray()总是返回-1和一个对象数组
- 在数组中的一个元素上设置多个值
- javascript处理一个对象数组以获得一个新的对象数组
- 作为一个二维数组,从ajax接收
- 你能用来自数组的属性名称生成一个对象吗
- 多维关联数组的最后一个索引
- 如何创建一个方法来验证数组的范围
- 循环以检查数组中的最后一个图像
- 在Javascript中将一个值和字符串数组转换为if语句
- 算法:从数组(javascript/angular)中按当前日期获取上一个和下一个事件
- 如何将一个对象添加到每个对象数组中
- 如何创建一个谷歌地图地理坐标数组
- 如何从另一个带下划线的数组中筛选带元素的数组
- 使用window.location.htm和匹配的URL数组(一个用于桌面,一个用于移动)将桌面网站重定向到移动
- Javascript排序多维数组-一个完整的例子
- 刽子手的游戏.2数组.一个需要相应地更新另一个