2014-04-27 2 views
0

각도 API가 외부 API와 통신하고 있습니다. Angular $ 리소스 호출에서 초기 뷰를 생성 할 수 있습니다. 내 문제는 ng-click에서 함수를 실행하는 양식이 있다는 것입니다. 그런 다음이 함수는 API를 다시 쿼리하고 동일한 범위 변수를 업데이트해야하지만 두 번째 $ 리소스 호출의 결과를 가져 와서 범위 변수를 업데이트 할 수는 없습니다. 내 컨트롤러에서

이 처음 뷰에 표시 데이터 취득이 초기 호출입니다 :

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

지금까지 너무 좋아, 뷰 업데이트와 내가 보여줄 수있는 JSON이를 API는 {{ weather.currently.temp }}과 {{geolocation}} 변수의 모든 데이터로 다시 전송됩니다. 이 시점에서

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

:

는 그러나, 나는 (제대로 컨트롤러에 이야기하도록 설정되어 있습니다) 제출시 그 같은 API에 또 다른 요청을하고 새로운 데이터를 반환해야 양식을 가지고 ,보기에서 {{weather}} 변수는 아무데도 업데이트되지 않습니다. 조금도. 함수 내에서 console.log 함수를 던지면 undefined 값을 얻으려고 시도 할 때 $scope.weather 값을 얻지 만 value 같은 console.log() 문을 대신 요청하면 유효한 JSON 개체를 얻습니다.

내 변수를 안에있는 $scope.weather에 할당하면 해당 값을 업데이트하여 뷰에 맞출 수 있습니다.

답변

0

이것이 내가 찾은 해결책입니다.이를 수행하는 대안/더 좋은 방법을 환영합니다.

분명히 $scope.weather은 여러 값을 참조합니다. 다시 말해, $ resource 및 $ http 메서드는 약속과 그 약속의 성격을 반환하기 때문에 $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); 
    }; 

    }); 

나는 멋진 Restangular 라이브러리 각도의 $resource 자신과 $http 서비스를 사용 전환 :

여기에 새로운 코드입니다. 이 변경에도 불구하고 $rootScope을 사용할 때까지 원래의 문제가 지속되었습니다. 나는 $resource$http을 사용하여이 이론을 테스트했으며, 여전히 문제가 있다는 것을 알고 있으므로 $scope.weather은 어쨌든 두 개의 개별 객체를 참조하기 때문에 후드 아래에서 $scope이고 약속은 Angular에서 작동한다는 것을 알았습니다.

관련 문제