Я видел ваш общий codepen. Так что Рикки, поскольку вы новичок в angularJS, я бы посоветовал вам прочитать документацию, связанную с angular 1, здесь: Angular JS - Документация
Теперь, перейдя к вашему требованию, вы должны вызвать внешний API и использовать данные из результата. Для этого вам нужно узнать о $http
в angularJS: $ http документации
Что касается кода, angular поддерживает внедрение зависимостей. Код, которым вы поделились, для меня загадка, как то, что делает функция fetch(postsUrl)
? Где декларация?
Сокращенно и кратко, реализация должна быть четкой и читаемой. Вот мой переделанный:
var app = angular.module("blogApp", []); //here you defined the ng-app module
//you are initializing a controller, you need to inject $http for calling the API
app.controller("mainCtrl", function($scope, $http) {
//Declaration of the posts object
$scope.posts = [];
//Onetime initialization of the API Endpoint URL
let postsUrl ="https://jsonplaceholder.typicode.com/posts";
//A method for getting the posts
function getPosts(){
//We are calling API endpoint via GET request and waiting for the result which is a promise
//todo: Read about the Promises
//A promise return 2 things either a success or a failure callback, you need to handle both.
//The first one is success and the second one is a failure callback
//So in general the structure is as $http.get(...).then(successCallback, failureCallback)
$http.get(postsUrl).then(function(response){
//In promises you get data in the property data, for a test you can log response like console.log(response)
var data = response.data;
$scope.posts = data; //Storing the data in the posts variable
//Note: you don't need to call the $scope.$apply() because your request is with in the angular digest process.
//All the request which are outside the angular scope required a $apply()
}, function(err){
//log the err response here or show the notification you want to do
});
}
//The final step is to call that function and it is simple
getPosts();
});
Приходите ко второй части, чтобы показать данные. Вы должны использовать документацию ng-repeat, это как ng-repeat="var item in collection track by $index"
. Это документация здесь нг-повтор
Итак, html должен быть в этой структуре:
<div ng-repeat="var post in posts track by $index">
{{post.userid}}
{{post.id}}
{{post.title}}
{{post.body}}
</div>
Теперь вы должны учиться и реализовывать.