为什么我的 ng-model 在 Firefox 中不使用 Typeahead 更新?

Why doesn't my ng-model update with Typeahead in Firefox?

在我使用 AngularJS I've got an input with a typeahead below for which I use 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 记录一个整数,但在 Firefox 中它只会记录 undefined.

我做了一个 plunker for it here 来说明我的意思(搜索 "one" 或 "two")。

它在 Chrome、Opera 和 Safari 中有效,但在 Firefox 中它以某种方式在控制台中显示 undefined。更奇怪的是它第一次只显示 undefined 。如果你 select 第二次它确实有效。

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

这是一个有趣的困境。

  • 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 并注释掉对模型的赋值。

    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