簡體   English   中英

AngularJS:如何從地理編碼功能更新數據模型?

[英]AngularJS: How do I update my data model from my geocoding function?

AngularJS和JavaScript新手,在這里。

我正在嘗試構建一個控制器,該控制器將提交地理編碼請求並使用結果更新其模型。 但是,我無法更新模型。

您可以在下面的小提琴中看到示例: http : //jsfiddle.net/3aszL/

在我的submitQuery函數中,我無法正確將地址解析方法的結果傳遞回search數組。 有指針嗎?

這是我的HTML:

<div ng-app="weather">
    <div ng-controller="SearchController as searchCtrl" class="container-fluid">
        <div>
            <form ng-submit="searchCtrl.submitQuery()" name="searchForm" role="form" class="">
                <div class="form-group">
                    <label for="searchInput">Search</label>
                    <input id="searchInput" class="form-control" type="text" ng-model="searchCtrl.search.geoQuery" placeholder="Enter your zip code...">
                    <input id="searchSubmit" class="btn btn-primary" type="submit">
                </div>
            </form>

            <h1>{{ searchCtrl.search.resultLatLng }}</h1>
        </div>

        <div class="playback">
            <small>searchCtrl.query = {{ searchCtrl.search.geoQuery }}</small>
            <small>searchCtrl.resultLatLng = {{ searchCtrl.search.resultLatLng }}</small>
        </div>
    </div>

</div>

和我的JS:

var app = angular.module("weather", []);

app.controller("SearchController", function($scope){
    var geocoder  = new google.maps.Geocoder();

    this.search = [
        {
            geoQuery: "",
            resultLatLng: "",
            resultCity: ""
        }
    ];

    this.submitQuery = function() {
        geocoder.geocode({'address': this.search.geoQuery}, function(result, status){
            if (status === google.maps.GeocoderStatus.OK) {
                search.resultLatLng = {
                    lat: result[0].geometry.location.lat(),
                    lng: result[0].geometry.location.lng()
                };
            } else {
                alert("Something went wrong: " + status);
                return false;
            }
        });
    };
});

我用一種有效的解決方案更新了您的小提琴,其中包括一些更正。 http://jsfiddle.net/3aszL/3/

主要問題:

  1. 您的this.search是數組中的對象。 它應該只是一個普通對象(無數組)。
  2. 您不能在另一個函數調用或回調中使用關鍵字this ,因為它將引用其他內容。 我通過添加that = this然后使用that的約定修復了它。 顯然, this是javascript中一個令人困惑的概念,但很重要。 閱讀上this位置: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
  3. 這是另一個棘手的問題,但是您有時需要在angular中運行$scope.$apply()才能更新視圖,尤其是如果該操作在異步操作的回調中運行時(如此處所示)。 這是一個過時的但不錯的閱讀: http : //jimhoskins.com/2012/12/17/angularjs-and-apply.html

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM