2017-05-30 16 views
0

webserviceを使用するjsファイルがあります。ここでは、ng-repeat指令で使用したい配列を定義します。 これは異なるファイルの角度指令を使用してjsファイルで定義された変数にアクセスする

<article ng-repeat="article in scopeArticles"> 
    <h1 class="content">content is {{article.title}} </h1> 
    <img src="{{article.imgSource}}" href="{{article.source}}"/> 
    <p>{{article.description}}</p> 
</article> 

JSが

var articles = []; 

$(document).ready(function() { 

    $.ajax({ 
     url: "https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=001034455" 
    }).then(function (data) { 
     $.each(data.articles, function (key, value) { 
      articles.push({ 
       title: value.title, 
       description: value.description, 
       source: value.url, 
       imgSource: value.urlToImage, 
       date: value.publishedAt 
      }); 

     }) 

    }) 

}); 
+5

'scopeArticles'と' articles'が異なる変数です! –

+1

また、 '$ .ajax'の代わりに' $ http'サービス(コントローラ内部)を使用すると、より角度のあるやり方で見えるようになります。 –

答えて

2

を提出私は現時点で持っているもの

htmlですがAngularJSでの作業中にjQueryについて少し忘れるようにしてください。 $http serviceを使用してデータを取得します。あなたのhtmlはコントローラなしでは動作しません。

(「URLにAPIキーを追加することを忘れないでください)以下の作業例を参照してください:

angular.module('app',[]) 
 
.controller("Ctrl",function($scope, $http){ 
 
     var ctrl = this; 
 
     
 
     ctrl.articles = []; 
 
     
 
     $http.get(
 
     'https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=' 
 
     ) 
 
     .then(function(response) { 
 
      angular.forEach(response.data.articles, function(value){ 
 
       ctrl.articles.push({ 
 
        title: value.title, 
 
        description: value.description, 
 
        source: value.url, 
 
        imgSource: value.urlToImage, 
 
        date: value.publishedAt 
 
       }); 
 
      }); 
 
     }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> 
 

 
<body ng-app="app" ng-controller="Ctrl as $ctrl"> 
 

 
<article ng-repeat="article in $ctrl.articles"> 
 
    <h1 class="content">content is {{article.title}} </h1> 
 
    <img ng-src="{{article.imgSource}}" href="{{article.source}}"/> 
 
    <p>{{article.description}}</p> 
 
</article> 
 

 
    
 
</body>

+0

チャームのように働いた。私はhtmlとjqueryを学んでいます。私はangularjsを追加することに決めました。あなたの助けに感謝します。 –

関連する問題