javascript - 在 AngularJS 项目中设置 Typeahead 下拉菜单的宽度

标签 javascript angularjs

我一直在努力使用 Bootstrap UI Typeahead 控件。我试图在运行时设置下拉框的宽度。 last SO question我询问了如何在运行时设置元素的宽度。虽然回答正确,但出于某种原因,答案在 Typeahead 指令的上下文中不起作用。目前,我在自己的指令中使用 Typeahead 控件,其定义如下:

.directive('myDirective', function () {
  return {
    restrict:'E',
    transclude: true,
    scope: {
      showLinks: '=?',
      query: '='
    },
    templateUrl: '/directives/my-directive.html',
    controller: function ($scope) {
      if (angular.isUndefined($scope.showLinks)) {
        $scope.showLinks = true;
      }

      $scope.getLocation = function(l) {
    var searchField = element.find('input');
        var width = searchField[0].offsetWidth;

        var dropdown = $element.find('.dropdown-menu');
        angular.element(dropdown[0]).css('width', (width + 'px'));    
      };
    }
  };
});

my-directive.html 看起来像这样:

<div style="width:100%;">
    <span>{{showLinks}}</span> <!-- renders just fine -->
    <input type="text" autofocus autocomplete="off" class="form-control" ng-model="query"
           typeahead="option as option.Name for option in getLocation($viewValue)"
           typeahead-min-length="3" typeahead-template-url="location.html" />
    <script type="text/ng-template" id="location.html">
      {{showLinks}} <!-- Never renders -->
      <span bind-html-unsafe="match.label | typeaheadHighlight:query"></span>
    </script>
</div>

如何设置下拉菜单的宽度,使其看起来与指令中的文本框宽度相同?我的文本框在不同的屏幕上大小不同。这就是为什么我不只是硬编码一个值。

最佳答案

typeahead 指令位置如何工作的一个有趣的副作用,让我们用一个简单的模板覆盖来做到这一点。活跃的区别是: ", 宽度: position.width+'px'"

当然效果是全局的。

angular.module("template/typeahead/typeahead-popup.html").run(["$templateCache", function($templateCache) {
  $templateCache.put("template/typeahead/typeahead-popup.html",
    "<ul class=\"dropdown-menu\" ng-show=\"isOpen()\" ng-style=\"{top: position.top+'px', left: position.left+'px', width: position.width+'px'}\" style=\"display: block;\" role=\"listbox\" aria-hidden=\"{{!isOpen()}}\">\n" +
    "    <li ng-repeat=\"match in matches track by $index\" ng-class=\"{active: isActive($index) }\" ng-mouseenter=\"selectActive($index)\" ng-click=\"selectMatch($index)\" role=\"option\" id=\"{{match.id}}\">\n" +
    "        <div typeahead-match index=\"$index\" match=\"match\" query=\"query\" template-url=\"templateUrl\"></div>\n" +
    "    </li>\n" +
    "</ul>\n" +
    "");
}]);

关于javascript - 在 AngularJS 项目中设置 Typeahead 下拉菜单的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26278701/

相关文章:

javascript - 尝试将 JSON 和 JS 与 jQuery 结合使用时遇到问题

javascript - 当历史返回时处理js执行

javascript - 使用 AngularJS 中的复选框按多个条件过滤数据

javascript - 使用 javascript 将 utc 日期时间按 timezoName 转换

javascript - 动态填充选择选项javascript

javascript - jQuery - 使用全局函数

javascript - 在 asp.net 中选择单选按钮值时隐藏/显示字段

javascript - AngularJS : Add click listener without using ng-click (for dynamicaly added data from a Json API)

javascript - Angular ng-if元素有类

javascript - ng-click 在 ionic 应用程序中没有做任何事情