【问题标题】:ng-blur overriding $scope variable? ng-model not updating with $scope variable ionic/angularng-blur 覆盖 $scope 变量? ng-model 未使用 $scope 变量 ionic/angular 进行更新
【发布时间】:2016-04-06 22:59:45
【问题描述】:

我正在用 ionic/angular 制作一个网络应用程序,用户可以在其中从以模式弹出的 Google 地图或从 Google 地图自动完成搜索框中选择位置。

为了获得最佳用户体验,我希望将用户在地图上选择的地址输入到搜索框中。

如果我先在地图上选择一个位置,然后通过在有效的搜索框中键入来更改位置。但是如果我先在搜索框中输入一个位置,然后尝试在地图上选择一个位置,输入框中的文本将保持不变。

我认为这与使自动完成工作所需的 ionic 指令有关

$scope.disableTap = function(){
    container = document.getElementsByClassName('pac-container');
    // disable ionic data tab
    angular.element(container).attr('data-tap-disabled', 'true');
    // leave input field if google-address-entry is selected
    angular.element(container).on("click", function(){
        document.getElementById('searchBar').blur();
    });
};

这里是搜索框声明

var input = document.getElementById('searchBar');
var autocomplete = new google.maps.places.Autocomplete(input);

我有一个与搜索框关联的 ng-model

<input type="text" id="searchBar" ng-focus="disableTap()" placeholder="Type address here..." 
ng-model="inputText">

我正在更新自动完成侦听器中的 $scope.inputText 变量,如下所示:

$scope.inputText = autocomplete.getPlace().formatted_address;

在地图监听器中像这样:

$scope.inputText = address.formatted_address;

blur 函数会覆盖 ng-model 吗?我弄错了吗?

如果我得到地图然后搜索框,但没有搜索框然后地图,谁能看到为什么我的 ng-model 更新?

任何帮助将不胜感激,谢谢

【问题讨论】:

  • 你能在 plunker 或 jsfiddle 上发布一个示例吗?

标签: angularjs google-maps ionic-framework blur angular-ngmodel


【解决方案1】:

这种性质的问题在这个地方到处都是,而且每次描述的问题都非常不同,以至于网站搜索失败。

简单的答案是,不要直接在 $scope 下存储值。这与礼仪无关,但一旦你了解了它的原因,就势在必行。您可以在下面的链接中阅读有关它的更多信息。

要解决您的问题,您应该在控制器或处理程序中执行类似的操作,

$scope.address.formatted = ...

并在您的视图中像这样访问它们,

<input type="text" placeholder="..." ng-model="address.formatted" name="address.formatted">

从链接中引用相关部分,

不同之处在于我们没有将数据直接存储在示波器上。现在,当 ng-model 想要写入时,它实际上是先读取,然后再写入。它从作用域中读取 person 属性,这将在子作用域中起作用,因为子作用域将向上搜索读取。一旦找到 person,它就会写入 person.first_name,这没问题。它只是工作。

这里是链接:Nested Scopes in AngularJS on jimhoskins.com

看到这是几个月前的问题,您可能已经解决了它,但还是留下了答案。 希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    相关资源
    最近更新 更多