0

I am able to console the result of the http call but when I bind it so that I can view on the html page I am unable to do it. Can someone help me with this? I am posting the controller code and the html below.

Controller code

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

}]);

HTML CODE For Index.htm

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

Code for Forecast.html

Forecast for {{city}}   <!-- THIS WORKS -->

{{ weatherResult.cnt }}  <!-- THIS DOES NOT WORK -->

Code for home.htm (EVERYTHING WORKS FINE HERE JUST POSTING FOR THE SAKE OF CLARITY)

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

console output correctly displays the objects:

Mistalis
  • 17,793
  • 13
  • 73
  • 97

4 Answers4

0

Maybe try and initialize $scope.weatherResult as an empty object in your controller so that AngularJS can watch it correctly.

Ripley511
  • 659
  • 4
  • 6
  • Hi There, I edited the post and added whole of the code. I tried what you suggested but unfortunately that doesn't seem to work. Can suggest something else? – Nipun Ahuja Jan 20 '17 at 23:38
0

Just put this assigning inside $scope.apply to notify angular engine that data was changes asynchronously so it should be processed correctly

$scope.$apply(function () {
    $scope.weatherResult = response.data; //IF I LOG THIS IT WORKS
});

Also good to add check that gigest cycle is not in progress now

if(!$scope.$$phase) {
  //$digest or $apply
}
VadimB
  • 5,533
  • 2
  • 34
  • 48
  • Hi There, I edited the post and added whole of the code. I tried what you suggested but unfortunately that doesn't seem to work. Can suggest something else? – Nipun Ahuja Jan 20 '17 at 23:38
  • This code is executed? Maybe some inline angular errors in console? Could you add console.log in apply directly to print `weatherResult` after assigning? It print correct value? – VadimB Jan 21 '17 at 06:33
  • Hi VladimB, The only thing that is missing from this code is my AppId from the URL to which I make the get request as I have removed it for safety reasons. Yes, if I console.log it, I get absolutely the right value. – Nipun Ahuja Jan 21 '17 at 07:53
  • Added the console output at the end. – Nipun Ahuja Jan 21 '17 at 08:03
  • Maybe you can create live fiddle as seems everething looks fine. – VadimB Jan 21 '17 at 08:58
0

Angular's inbuilt 2-way data binding does not work on http responses which is a known issue. Use $timeout to manually kick in the 2-way data binding and thereby initiating the digest cycle.

$scope.getWeather= function(){
    $http({
        url: "http://api.openweathermap.org/data/2.5/forecast/daily?AP&units=metric",
        method: "GET",
        params: {q: $scope.city, cnt:2}
 })
    .then(function(response){
           $timeout(function(){
             $scope.weatherResult = response.data; 
          }, 0);

    });
 }
}]);

Note the $timeout timer is set at 0ms to immediately kick in the digest cycle.

Jeyenth
  • 472
  • 4
  • 10
  • Hi There, I edited the post and added whole of the code. I tried what you suggested but unfortunately that doesn't seem to work. Can suggest something else? – Nipun Ahuja Jan 20 '17 at 23:38
0

Correct Code posted. I was assigning the http get call to $scope.variable, I just removed it and it started working. Thanks