【发布时间】:2016-10-02 14:32:52
【问题描述】:
我不知道如何使用指令访问和更改输入 ngModel 值。问题的结果是,当我选择所需的地址时,模型的地址值没有更新……它只是设置为我实际输入到输入中的内容,而不是输入的最终值。
我输入“830”:
我选择“8300 Fauntleroy Way Southwest, Seattle, WA, United States”:
结果值:
{
address: '830'
}
期望值:
{
address: '8300 Fauntleroy Way Southwest, Seattle, WA, United States'
}
在 AngularJS 中我可以这样做:
(function() {
'use strict';
angular
.module('casemanagerApp')
.directive('googleplace', googleplace);
function googleplace() {
var directive = {
require: 'ngModel',
link: link
};
return directive;
function link(scope, element, attrs, model) {
var options = {
types: [],
componentRestrictions: {}
};
scope.gPlace = new google.maps.places.Autocomplete(element[0], options); // jshint ignore:line
google.maps.event.addListener(scope.gPlace, 'place_changed', function() { // jshint ignore:line
scope.$apply(function() {
model.$setViewValue(element.val());
});
});
}
}
})();
但现在我正在尝试将其转换为 Angular 2,我有点卡住了。以下是我目前对转换的了解:
/// <reference path="../../../../typings/browser/ambient/googlemaps/index.d.ts"/>
import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
selector: '[google-places]'
})
export class GooglePlaces implements OnInit {
constructor(private _el: ElementRef) { }
ngOnInit() {
let gPlace = new google.maps.places.Autocomplete(this._el.nativeElement);
google.maps.event.addListener(gPlace, 'place_changed', () => console.log(this._el.nativeElement));
}
}
用法:
<input type="text"
ngControl="address"
placeholder="Enter a location"
[(ngModel)]="subject.address"
#address="ngForm"
google-places
required>
问题的核心是我不明白如何在 Angular 2 中做相当于 model.$setViewValue(element.val()); 的操作。
任何帮助将不胜感激。
【问题讨论】:
-
这看起来相关stackoverflow.com/questions/36106350/…也许你可以得到一些想法。
-
嗨@GünterZöchbauer。不幸的是,这些解决方案对我不起作用。我创建了一个 Plunker 来更好地说明这个问题。 plnkr.co/edit/1xMjzo
-
Thierrys 的方法怎么样?
-
@GünterZöchbauer 是的,这也不起作用。它们都只是改变了输入的值而不更新模型的值。
标签: angular angular2-directives