在导入的JSON对象AngularJS中获取一个数组

Grab an array within imported JSON object - AngularJS

本文关键字:数组 一个 获取 导入 JSON 对象 AngularJS      更新时间:2023-09-26

我正在构建一个快速的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指令中直接输入模板,就可以解决这个问题了!感谢大家的帮助!