0

我有一个与外部 API 通信的 Angular 应用程序。我能够从 Angular $resource 调用中生成初始视图。我的问题是我有一个在 ng-click 上运行函数的表单。然后该函数再次查询 API 并应该更新相同的范围变量,但我无法获得第二个 $resource 调用的结果以更新范围变量。

在我的控制器中,这是获取最初显示在视图中的数据的初始调用:

// Initial weather and geolocation data var Weather = $resource('http://example.com/:method'); Weather.get({method: 'current'}).$promise.then(function(weather) { // Success $scope.weather = weather.weather; $scope.geolocation = weather.location; }, function(error) { // Failure $scope.weather = error; });

到目前为止一切顺利,视图更新了,我可以显示 API 发回的 JSON{{ weather.currently.temp }}以及 {{ geolocation }} 变量中的所有数据。

但是,我有一个表单(它已正确设置为与控制器对话),在提交时应该向同一个 API 发出另一个请求并返回新数据:

// Search functionality $scope.weatherLookup = function(query) { $http.get('http://example.com/location/' + query).then(function (value) { $scope.weather = value; }); };

此时,在视图中,{{ weather }} 变量不会在任何地方更新。完全没有。如果我在尝试获取的值时在函数中抛出一个console.log函数,但是当我在同一语句中请求时,我确实得到了一个有效的 JSON 对象。weatherLookupundefined$scope.weathervalueconsole.log()

如何将该value变量分配给$scope.weather内部$scope.weatherLookup,以便它可以更新该值并将其冒泡到视图中?

4

1 回答 1

0

这是我找到的解决方案 - 我欢迎替代/更好的方法来做到这一点。

显然$scope.weather引用了多个值。也就是说,因为 $resource 和 $http 方法返回 promises 和这些 promises 的性质,$scope.weather就视图和控制器而言,实际上可以引用两个单独的对象。我解决问题的方法是$rootScope确保weather始终覆盖同一个对象。

这是新代码:

'use strict';

angular.module('myApp')
  .controller('WeatherCtrl', function ($scope, Restangular, $rootScope) {

    // Get initial weather data (NOW WITH $rootScope)
    Restangular.one('current').get().then(function(weather) {
      $rootScope.weather = weather.weather;
      $scope.geolocation = weather.location;
    });

    // Search functionality
    $scope.weatherLookup = function(query) {
      Restangular.one('location/' + query).get().then(function(newWeather) {
        $rootScope.weather = newWeather;
        console.log($rootScope.weather);
      });
      console.log($rootScope.weather);
    };

  });

我从使用 Angular 自己的$resource$http服务切换到了很棒的Restangular库。尽管发生了这种变化,但最初的问题一直存在,直到我使用$rootScope. $resource我使用并测试了这个理论$http,它仍然有效,所以我知道问题在于,由于Angular 中的工作方式和承诺,问题是$scope.weather在某种程度上分裂并引用了引擎盖下的两个单独的对象。$scope

于 2014-04-28T14:34:07.860 回答