简体   繁体   中英

Angular display response in HTML from Ajax GET

Apologies in advance for asking a dumb question. I've related a dozen plus related posts without success.

Here's my controller.

app.controller('testController', function ($scope) {
    var myApi = 'https://jsonplaceholder.typicode.com/posts';
    $.ajax({
        url: myApi,
        type: 'GET',
        success: function (response) {
            console.log(response[0]);
            $scope.response = response[0]
        },
        error: function (response) {
            console.log("could not retrieve list.");
            console.log(response.message);
        }
    });
});

My HTML is

<body ng-app="myApp" class="text-center">
    <div id="foo" ng-controller="testController">
        {{response.title}}
    </div>
...
</body>

And I can see in the browser console that I do get the desired content in the GET response

[Log] {userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit↵suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto"} (javascript.js, line 27)

...but the text doesn't show up in the rendered HTML. What am I doing wrong?

Answering my own question here for posterity. I switched from Ajax to this $http method. As you can tell, I'm super brand new to this. If any seasoned experts are reading this, can you comment on the two approaches here and describe anything I'm probably missing?

app.controller('testController', function ($scope, $http) {
    $http({
        method: 'GET',
        url: 'https://jsonplaceholder.typicode.com/posts',
    }).then(function (response) {
        console.log(response.data[0])
        $scope.response = response.data[0];
        console.log($scope.response)
        //alert($scope.response);
    });
});

<body ng-app="myApp" class="text-center">
    <div id="foo" ng-controller="testController">
        {{response.title}}
    </div>
...
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM