如何显示我的请求响应.在HTML中使用angularJS



别无礼,我刚学angularJS

我写了一个get函数,它请求一个API,给我一些查克诺里斯的事实。

我的问题很简单:当我点击我的按钮时,如何在我的HTML中显示响应。

实际上,当我点击我的按钮,我得到我的chuckNorrisFact句在我的控制台

Thanks a lot

我的html

<!DOCTYPE html>
<html lang="FR">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Random Chuck Norris jokes</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>

<body ng-app="mainApp">
<div ng-controller="mainCtrl">
<button ng-click="generateRandomJoke()"> have fun</button>
</div>
<p></p>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="controllers/controllers.js"></script>
</html>

这里是我的controllers.js:

var app = angular.module('mainApp', []);
app.controller('mainCtrl', function ($scope, $http) {
function getJoke() {
$scope.generateRandomJoke = function () {
$http({
method: "GET",
url: "https://api.chucknorris.io/jokes/random",
})
.then(function mySuccess(response) {
$scope = response.data;
console.log($scope.value)
}, function myError(response) {
console.log("erreur : ", response.data.errors);
});
}}
getJoke();
})


您正在做的事情不起作用,因为您正在用字符串覆盖整个$scope变量。你要做的是将字符串作为变量添加到$scope:

var app = angular.module('mainApp', []);
app.controller('mainCtrl', function ($scope, $http) {
function getJoke() {
$scope.generateRandomJoke = function () {
$http({
method: "GET",
url: "https://api.chucknorris.io/jokes/random",
})
.then(function mySuccess(response) {
$scope.joke = response.data.value;
console.log($scope.joke)
}, function myError(response) {
console.log("erreur : ", response.data.errors);
});
}}
getJoke();
})

现在您可以使用{{ }}来访问当前控制器的scope内部的变量。

<!DOCTYPE html>
<html lang="FR">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Random Chuck Norris jokes</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>

<body ng-app="mainApp">
<div ng-controller="mainCtrl">
<button ng-click="generateRandomJoke()"> have fun</button>
<p>{{ mainCtrl.joke }}</p> <!-- you can either write mainCtrl.joke or simply joke -->
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="controllers/controllers.js"></script>
</html>

参见Plunker。

最新更新