【问题标题】:Why doesn't my ng-model update with Typeahead in Firefox?为什么我的 ng-model 没有在 Firefox 中使用 Typeahead 进行更新?
【发布时间】:2015-06-19 13:57:28
【问题描述】:

在我使用AngularJS 构建的网站中,我有一个输入,下面有一个输入,我使用angular-typeahead。它在 Chrome、Opera 和 Safari 中运行良好,但在 Firefox 中则不行。问题似乎是在 Firefox 中,当我单击预先输入的建议时,模型没有更新。

我的 html 看起来像这样:

<input class="typeahead" sf-typeahead type="text" datasets="userDataset" ng-model="searchUser" >
<button ng-click="sendToUser(searchUser.id)" class="btn">Send</button>

在我的控制器中,我有这个简单的功能:

$scope.sendToUser = function(userId){
    console.log(userId);
    // More code here..
}

在 Chrome、Opera 和 Safari 中,它为 userId 记录一个 int,但在 Firefox 中它只记录 undefined

我创建了一个plunker for it here 来表明我的意思(搜索“一”或“二”)。

它适用于 Chrome、Opera 和 Safari,但在 Firefox 中它以某种方式在控制台中显示undefined。更奇怪的是它第一次只显示undefined。如果您再次选择某项内容,它确实有效。

有谁知道为什么这在 Firefox 中不起作用,最重要的是,我该如何解决?欢迎所有提示!

【问题讨论】:

  • 我在 Chrome 和 FF 中试用了你的 Plunker。两者似乎都运作良好。有时可以通过在 FF 中的 TypeAhead 外部单击来“取消选择”模型。因此模型被正确绑定,但随后未绑定。当我点击“发送”按钮并做出选择时,该错误不会再次出现,直到我做出另一个选择。
  • @DaveAlperovich - 好的,你知道我们如何在使用 Firefox 时保持模型被选中吗?
  • 还没有。非常奇怪的行为。模型解析器正在被触发,这意味着单击事件以某种方式启动了一个摘要循环(已经很奇怪),并使用当前索引作为值。两者都非常奇怪。我还找不到与此相对应的绑定事件。
  • 是的,我知道发生了什么。 ng-model 绑定与对象分配冲突。选择后,您将“searchUser”设置为对象的值。但是,在摘要循环运行之后的那一刻,“searchUser”变成了一个绑定到输入的字符串。此字符串没有子 ID。

标签: javascript angularjs firefox typeahead.js angular-ngmodel


【解决方案1】:

这是一个有趣的困境。

  • TypeAheadng-model 值设置为选中的对象

  • 在运行摘要循环的任何事件(如点击)上,框架强制执行ng-model 绑定,为模型值分配一个绑定到输入的字符串。

  • FireFox,不像 Chrome 似乎强制执行此行为。 Chrome 输入可能允许设置对象值(只是猜测)。


解决方法是更改​​您的输出绑定:

<input class="typeahead" sf-typeahead type="text"  datasets="userDataset" 
outputval="searchUser" ng-model="a" options="exampleOptions">

outputval 是我们的预期值。我绑定到一个随机范围变量a,因为该指令需要并使用模型绑定。

在指令内部,我更改了updateScope 函数以将选定的值设置为scope.outputval 并注释掉对Model 的赋值。

    function updateScope (object, suggestion, dataset) {
      scope.$apply(function () {
        var newViewValue = (angular.isDefined(scope.suggestionKey)) ?
            suggestion[scope.suggestionKey] : suggestion;
        console.log(newViewValue);    
        //ngModel.$setViewValue(newViewValue);
        scope.outputval = newViewValue;
      });
    }

试试我的Plunker

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多