根据Angular $资源更新范围变量

时间:2014-04-27 03:21:42

标签: javascript json angularjs angular-resource angular-http

我有一个与外部API通信的Angular应用程序。我能够从Angular $资源调用生成初始视图。我的问题是我有一个在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使用{{ weather.currently.temp }}发回的JSON以及{{geolocation}}变量中的所有数据。

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

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

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

如何将console.log()变量分配给value内的$scope.weather,以便它可以更新该值并让它冒泡到视图中?

1 个答案:

答案 0 :(得分: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测试了这个理论,它仍然有效,所以我知道问题是$scope.weather以某种方式分裂和引用两个独立的对象,因为$scope {1}}并承诺在Angular中工作。

相关问题