0

I have a js file to consume a webservice and here i define an array that i want to use in a ng-repeat directive. this is what i have at the moment

html

<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 file

  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
            });

        })

    })

});
2
  • 5
    scopeArticles and articles are different variables! Commented May 30, 2017 at 11:02
  • 1
    Also it is better use $http service (inside a controller) instead of $.ajax to make it look and work in a more angularjs-way. Commented May 30, 2017 at 11:09

1 Answer 1

2

Try to forget a bit about jQuery while working with AngularJS. Use $http service to fetch your data. And your html will not work without controller.

See the working example below (don't' forget to add your API key to the URL):

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm. I'm learning html and jquery and i decided to add angularjs so thank you for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.