【问题标题】:AngularUI Boostrap typeahead doesn't select when item is clicked单击项目时,AngularUI Boostrap typeahead 不选择
【发布时间】:2014-07-23 09:40:55
【问题描述】:

我是 Angular 的新手,并且遇到 AngularUI 引导工具包的问题,​​即单击下拉列表中的某个项目时,文本框不会填充完整的值。点击后下拉框消失,只留下输入的字符。

这是代码(开始在文本框中输入“间谍”)

http://plnkr.co/edit/WYLn0c6HvuOLl1pJBCxa?p=preview

<body>
  <div data-ng-controller="AssetCtrl">
    <br />
    <input type="text" ng-model="selected" typeahead="asset.ticker as typeaheadLabel(asset) for asset in assets | filter:{ticker:$viewValue}" class="form-control">

  </div>



  <script>
    var ConsoleApp = angular.module('ConsoleApp', ['ui.bootstrap']);
    function AssetCtrl($scope) {
      $scope.assets = [{
        "assetClass": "stock",
        "ticker": "spy",
        "description": "S&P"
      }];

      $scope.typeaheadLabel = function(item) {
        return item.ticker.toUpperCase() + ' (' + item.assetClass + ') - ' + item.description;
      };
    }

    ConsoleApp.controller('AssetCtrl', AssetCtrl);
  </script>
</body>

【问题讨论】:

    标签: javascript angularjs twitter-bootstrap angular-ui


    【解决方案1】:

    似乎问题出在typeaheadLabel 函数中,该函数在计算模型值时被评估,并且item 通常为空。您可以在 label 函数上添加一些防御性 null 检查,以便值评估不会被破坏,因为这是 typeahead 实际上与模型的值匹配的内容:-

    来自 TypeAhead 的片段

    return {
            itemName:match[3],
            source:$parse(match[4]),
            viewMapper:$parse(match[2] || match[1]), //<-- here if the function evaluation is undefined which is in your case it will take the value of ticker propery as modelValue
            modelMapper:$parse(match[1])
          };
    

    解决方法1:-

      $scope.typeaheadLabel = function(item) {
        if(!item || !item.ticker) return;
        return item.ticker.toUpperCase() + ' (' + item.assetClass + ') - ' + item.description;
      };
    

    Plnkr

    我建议的另一种方法是在 viewModel 本身中添加一个 displayName 属性。例如:-

    解决方法 2:

       $scope.assets = [{
            "assetClass": "stock",
            "ticker": "spy",
            "description": "S&P"
          },{
            "assetClass": "stock",
            "ticker": "asd",
            "description": "A&D"
          }].map(typeaheadLabel);
    
    
          function typeaheadLabel(item) {
            item.displayName = item.ticker.toUpperCase() + ' (' + item.assetClass + ') - ' + item.description;
            return item;
          };
    

    并将displayName 指定为别名asset.ticker as asset.displayName for asset in assets

    Plnkr2

    【讨论】:

    • 谢谢,这很有帮助!您的第二个解决方案 (displayName) 仅适用于 Angular 1.2 而不是当前的 1.3.x beta。我不知道为什么,但是一旦我改变了它并整合了你的解决方案,一切都像 Plnkr 显示的那样工作。
    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 2014-06-30
    • 1970-01-01
    相关资源
    最近更新 更多