简体   繁体   English

角的$ scope不更新?

[英]angular's $scope not updating?

I'm trying to create a basic weather app based on the user's location, which I take using javascript geolocation service. 我正在尝试根据用户的位置创建一个基本的天气应用程序,该应用程序是使用javascript地理位置服务。 Everything regarding the location and weather works as expected. 有关位置和天气的所有操作均按预期进行。
My problem is when the user reject the location request, what I want to do is hide the weather data (which I can't get) and show an appropriate message. 我的问题是,当用户拒绝位置请求时,我想做的就是隐藏天气数据(我无法获取)并显示适当的消息。
HTML: HTML:

<body ng-app="weatherApp">
  <div class="container text-center" style="margin-top: 15vh" ng-controller="weatherCtrl">
    <h1>Local Weather App</h1>
    <h3>{{error}}</h3>
    <div class="row" ng-hide="showError">
      <div id="loc-col" class="col-xs-3 col-xs-offset-1">
        <h3>{{data.name}}</br>
        <small>{{data.sys.country}}</small></h3>
      </div>
      <div id="temp-col" class="col-xs-4">
        <h3>{{data.main.temp}} {{degree}}&deg;</h3>
      </div>
      <div id="weather-col" class="col-xs-3">
        <h3>{{data.weather[0].main}} </br><small>{{data.weather[0].description}}</small> </h3>
      </div>
      <div id="icon-col" class="col-xs-6 col-xs-offset-3">
        <img id="icon" class="img-responsive" ng-src="{{icon}}">
      </div>
    </div>
  </div>
</body>

The error message should be in the <h3> below the h1. 错误消息应位于h1下面的<h3>中。

JS: JS:

'use strict';
var app = angular.module('weatherApp', []);

app.factory('weatherFactory', ['$http', function($http){
  var weather = {};

  weather.getWeather = function(lat, lon){
    return $http.jsonp("http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+lon+"&units=metric&callback=JSON_CALLBACK");
  };
  return weather;
}]);

app.controller('weatherCtrl', ['$scope', 'weatherFactory', '$http', function($scope, weatherFactory, $http){
  $scope.degree = "C";

  $scope.error = "";
  $scope.showError = false;

  var icons = { };

  function getWeatherFromPos(position){
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    weatherFactory.getWeather(lat,lon).success(
            function(data){
              $scope.data = data;
              $scope.icon = icons[data.weather[0].icon];
            }
          ).error(function(error){
            setError(error);
          });
  }

  function setError(error){
    $scope.showError = true;
    $scope.error = error;
  }

  //THIS IS THE RELEVANT CODE:
  if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        function(position) {
          getWeatherFromPos(position);
        }, 
        function() {
          //EXECUTED UPON REJECTION
          setError("Geolocation service failed.");
        }
      );
    }
    else {
      setError("Your browser doesn't support geolocation.");
    }
}]);

When I open up the consoler and I execute the following: 当我打开控制台程序并执行以下命令时:

angular.element($(".row")).scope().error
"Geolocation service failed."

So somehow the variable do get updated, but the error message is not shown and the weather data is not hidden. 因此,该变量确实以某种方式得到了更新,但未显示错误消息并且未隐藏天气数据。

Your setError function execute out of $digest cycle of angular. 您的setError函数在$digest角度周期之外执行。 You can do follow: 您可以按照以下步骤操作:

  function setError(error){
    $scope.showError = true;
    $scope.error = error;
    $scope.$apply();
  }

or 要么

function setError(error){
    $scope.$apply(function () {
       $scope.showError = true;
       $scope.error = error;
   }
}

PS: It is concerned about setError("Geolocation service failed."); PS:它担心setError("Geolocation service failed."); and setError("Your browser doesn't support geolocation."); setError("Your browser doesn't support geolocation."); .

But for setError(error) it is not ok to use $apply because it is already inside $digest loop (there is no need to call $apply method). 但是对于setError(error)来说,使用$apply是不合适的,因为它已经在$digest循环内$digest (不需要调用$apply方法)。 Remember you need to call $apply only after you made some changes outside of angular digest loop. 请记住,只有在角度摘要循环之外进行了一些更改之后,才需要调用$apply See more about it https://docs.angularjs.org/api/ng/type/ $rootScope.Scope#$apply 进一步了解它https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope#$ apply

我想谢谢您错过了ng-bind:

<h3 ng-bind="error">{{error}}</h3>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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