0

後、私はGoogleの-場所angularjs単一ページのアプリケーションにサービスとして実行するものとし、実行時に一度初期化されなければならないオートコンプリートの入力が必要です。ナビゲーションの場合、goolge-placesの初期化された要素と適切なスコープが破棄されます。再利用グーグル-場所オートコンプリート入力ページナビゲーション


場所の入力フィールドを含むページに移動した後、場所の入力フィールドを再利用します。メソッドelement.replaceWith()でうまくいきます。


要素を交換した後、私は、「リセット」ボタンの入力をリセットすることができません。新しい生成スコープを "リセット"ボタンと古いスコープ変数にバインドする方法を教えてください。古いスコープと要素はナビゲーションイベントによって破棄されるためですか?

.factory('myService', function() { 
    var gPlace; 
    var s, e; 
    var options = { 
     types: [], 
     componentRestrictions: {country: 'in'} 
    }; 
    function init() { 

    } 
    function set(element, scope) { 
    console.log('set'); 
    if (!gPlace) { 
     e = element; 
     gPlace = new google.maps.places.Autocomplete(element[0], options); 

     google.maps.event.addListener(gPlace, 'place_changed', function() { 
      scope.$apply(function() { 
       scope.place.chosenPlace = element.val(); 
      }); 
     }); 
    } else { 
     element.replaceWith(e); 
    } 
    } 
    init(); 
    return { 
    'init':init, 
    'set':set 
    }; 
}); 

ナビゲーション(要素及び範囲破壊)は、「削除」ボタンによってトリガされるng-ifディレクティブによってこのplunkでシミュレートされます。そして、このサービスを使用していますディレクティブを作成

.service('myPlaceService', function(){ 
var _place; 

this.setPlace = function(place){ 
    _place = place; 
} 

this.getPlace = function(){ 
    return _place; 
} 

return this; 
}); 

:あなたはコントローラやディレクティブの中で最後に選択した場所と共有、それを保持しているサービスを作成することができますしたい場合は

see here plunk

答えて

0

.directive('googlePlaces', function(myPlaceService) { 
return { 
    restrict: 'E', 
    scope: { 
    types: '=', 
    options: '=', 
    place: '=', 
    reset: '=' 
    }, 
    template: '<div>' + 
    '<input id="gPlaces" type="text"> <button ng-click="resetPlace()">Reset</button>' + 
    '</div>', 
    link: function(scope, el, attr){ 
    var input = document.querySelector('#gPlaces'); 
    var jqEl = angular.element(input); 
    var gPlace = new google.maps.places.Autocomplete(input, scope.options || {}); 
    var listener = google.maps.event.addListener(gPlace, 'place_changed', function() { 
     var place = autocomplete.getPlace(); 
     scope.$apply(function() { 
      scope.place.chosenPlace = jqEl.val(); 
      //Whenever place changes, update the service. 
      //For a more robust solution you could emit an event using scope.$broadcast 
      //then catch the event where updates are needed. 
      //Alternatively you can $scope.$watch(myPlaceService.getPlace, function() {...}) 
      myPlaceService.setPlace(jqEl.val()); 
     }); 

    scope.reset = function(){ 
     scope.place.chosenPlace = null; 
     jqEl.val(""); 
    } 

    scope.$on('$destroy', function(){ 
    if(listener) 
     google.maps.event.removeListener(listener); 
    }); 
    }); 
    } 
} 
}); 

このように使用できます:

<google-places place="vm.place" options="vm.gPlacesOpts"/> 

ここで、助けを

vm.gPlacesOpts = {types: [], componentRestrictions: {country: 'in'}} 
+0

おかげで、私は最後の場所に保存されません。毎回繰り返して初期化することなく入力場所を再利用する必要があります。 – usher

関連する問題