[英]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>
思考?
您尚未指定控制器。
<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>
更改
<newsInfo info="news"></newsInfo>
至
<news-info info="news"></news-info>
$scope.getNews = function(){
return $http.get('URL').success(function(data) {
return data.news;
})
};
^这,只需更改它,以便成功函数只返回新闻!
在回答我自己的问题时,我应该指出每个人的答案都是正确的。 代码有多个错误,但最后的错误是通过执行以下操作修复的:
显然,我必须将newsInfo.html doc上传到S3存储桶,并将该URL用作“Cross origin requests are only supported for HTTP.”
但随后Angular使用错误阻止了该外部源: "$sce:insecurl Processing of a Resource from Untrusted Source Blocked"
。
因此,由于html模板非常简单,我只是通过直接在.js指令中输入模板来解决这个问题,并且它有效! 谢谢大家的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.