我正在构建一个快速的 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;
});
}]);
然后将数据添加到 Controller 中的 $scope 对象中,我这样做:
app.controller('MainController', ['$scope','getNews', function($scope, getNews) {
getNews.success(function(data)) {
$scope.newsInfo = data.news;
});
});
但它不起作用。当我加载 html 页面时,只有白色。我的想法是,这是因为它没有获取 JSON 中的数组并使用该数据来填充我设置的 HTML 指令。
新闻信息.js:
app.directive('newsInfo',function(){
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl:'newsInfo.html'
};
});
新闻信息.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>
关于javascript - 在导入的 JSON 对象中获取一个数组 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978415/