我能够控制 http 调用的结果,但是当我绑定它以便可以在 html 页面上查看时,我无法做到这一点。有人可以帮我弄这个吗?我在下面发布控制器代码和 html。
控制器代码
//module
var weatherApp = angular.module('weatherApp',['ngRoute' , 'ngResource']);
//Routes
//http://api.openweathermap.org/data/2.5/forecast/daily?APPID=metric
weatherApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl:'pages/home.htm',
controller:'homeController'
})
.when('/forecast', {
templateUrl:'pages/forecast.htm',
controller:'forecastController'
});
});
//services
weatherApp.service('cityService' ,function() {
this.city ="San Jose, CA";
});
//controllers
weatherApp.controller('homeController' ,['$scope', 'cityService', function($scope , cityService) {
$scope.city = cityService.city;
$scope.$watch('city' , function () {
cityService.city = $scope.city;
});
}]);
$scope.city = cityService.city;
console.log($scope.city);
$http({
url: "http://api.openweathermap.org/data/2.5/forecast/daily?APPID==metric",
method: "GET",
params: {q: $scope.city, cnt:2}
}).then(function(response){
$scope.weatherResults = response.data;
console.log($scope.weatherResults);
});
}]);
Index.htm 的 HTML 代码
<!DOCTYPE html>
<html lang="en" ng-app="weatherApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/navbar.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-resource.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<!-- NAVBAR -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<a class="navbar-brand" href="#">Accurate Weather</a>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Home</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<!-- NAVBAR ENDS-->
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
Forecast.html 的代码
Forecast for {{city}} <!-- THIS WORKS -->
{{ weatherResult.cnt }} <!-- THIS DOES NOT WORK -->
home.htm 的代码(这里一切正常,只是为了清楚起见而发布)
<div class = "row">
<div class = "col-md-6 col-md-offset-3">
<h4>Forecast by city</h4>
<div class="form-group">
<input type="text" ng-model="city" class="form-control" />
</div>
<a href="/weatherApp/index.htm#!/forecast" class="btn btn-primary">Get forecast </a>
</div>
</div>