2015-07-04 13 views
0

我處於必須將LntLng變量傳遞給使用這些緯度和經度變量作爲URL參數的$ http.get請求的服務的情況。從指令到角度的服務共享變量的可能性

我通過使用本地存儲,這localStorage的方法在某種程度上是有用的,但它只能一次,不能設置變量更新爲新值,如果用戶改變他的位置,其他一些place.I需要更新變量嘗試了一些方法每次用戶改變地址時新的優化。

.factory('someFactory', function($http) { 
    return { 
      get: function(result) { 
       var latitude='value from directive variable'; 
       var longitude='value from directive variable'; 

       $http.get('http://www.someapi.com/?longitude=' + longitude + '&latitude='+ latitude + '&customer_number=00000') 
       .success(function(result) { 

       }); 
      } 
     } 
}); 

指令:

popupPromise.then(function(el) { 
    var searchInputElement = angular.element(el.element.find('input')); 

    scope.selectPlace = function(place) { 
      ngModel.$setViewValue(place); 
      map.setCenter(place.geometry.location); // from here i will get new updated place object with variable i need..My problem is to access the 'place' object in service . 

      ngModel.$render(); 
      console.log('rendering'); 
      el.element.css('display', 'none'); 
      $ionicBackdrop.release(); 
    }; 
}; 

注:我要去只是「地方」的對象被更新後,採取從指令值,就會發出指令後,以服務價值是滿載。

請提出任何建議。

回答

0

您可以在指令(如位值從指令到來屬性)很容易地通過$watch$observe實現這一目標。

//服務

.factory('someFactory', function($http) { 
    return { 
     get: function(lat, lng) { 
      return $http.get('http://www.someapi.com/?longitude=' + lng + '&latitude='+ lat + '&customer_number=00000'); 
     } 
    } 
}); 

//指令

directives.directive('someDirective', ['someFactory', function(someFactory) { 
    return { 
     link: function($scope, element, attr) { 
      function responseHandler() { 
       // Your code on response from the API 
       ngModel.$setViewValue(place); 
       map.setCenter(place.geometry.location); // from here i will get new updated place object with variable i need..My problem is to access the 'place' object in service . 

       ngModel.$render(); 
       console.log('rendering'); 
       el.element.css('display', 'none'); 
       $ionicBackdrop.release(); 
      } 

      // Look for the change in place entered by user 
      attr.$observe('place', function(newValue) { 
       if (newValue) { 
        someFactory.get(newValue.lat, newValue.lng).then(responseHandler); 
       } 
      }); 

      //    OR        // 
      // Watch for any scope variable (if you have place object as stored in Scope) 
      $scope.$watch('place', function(newValue) { 
       if (newValue) { 
        someFactory.get(newValue.lat, newValue.lng).then(responseHandler); 
       } 
      }); 
     }, 
    }; 
}]);