[英]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/
主要問題:
this.search
是數組中的對象。 它應該只是一個普通對象(無數組)。 this
,因為它將引用其他內容。 我通過添加that = this
然后使用that
的約定修復了它。 顯然, this
是javascript中一個令人困惑的概念,但很重要。 閱讀上this
位置: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this 。 $scope.$apply()
才能更新視圖,尤其是如果該操作在異步操作的回調中運行時(如此處所示)。 這是一個過時的但不錯的閱讀: http : //jimhoskins.com/2012/12/17/angularjs-and-apply.html 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.