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

标签 javascript json 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; 
        }); 
}]);

然后将数据添加到 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>

示例:https://jsfiddle.net/bhv0zvhw/3/

关于javascript - 在导入的 JSON 对象中获取一个数组 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978415/

相关文章:

javascript - 如何创建具有文本框 "auto-filled"的链接?

javascript - html改变div内容

javascript - 使用 javascript 打开 Google Chrome 浏览器的新选项卡窗口时出现问题

javascript - 我们是否需要 Web 服务器(如 Apache)来访问 .json 文件?

oop - 使用 oop 继承的 angularjs

javascript - Uncaught ReferenceError : Tankvalue is not defined

javascript - 如何改进这个包含基本重复逻辑的 toggleClass 函数?

javascript - amcharts 4中的24小时雷达图

ajax - 计算 Json 字符串中的重复值并将值和标签存储在另一个字符串中

javascript - Web API - 保留字?