Customizing Typeahead Drop Down Width in Angular Project

I've been struggling with customizing the Bootstrap UI Typeahead component. I am attempting to dynamically adjust the width of the dropdown box. The solution provided in the previous Stack Overflow question I asked worked in a different context, but for some reason, it doesn't seem to work with the Typeahead directive. Currently, I have integrated the Typeahead component into my own directive, which is defined as follows:

.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'));    
      };
    }
  };
});

The content of my-directive.html is as follows:

<div style="width:100%;">
    <span>{{showLinks}}</span> <!-- renders correctly -->
    <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}} <!-- does not render -->
      <span bind-html-unsafe="match.label | typeaheadHighlight:query"></span>
    </script>
</div>

Is there a way to dynamically adjust the width of the dropdown menu to match the width of the textbox in my directive? The size of the textbox varies on different screens, so I cannot simply hard-code a fixed value.

Answer №1

A fascinating consequence of the way the typeahead directive position functions is that you can achieve this through a simple template override. The key difference is: ", width: position.width+'px'"

Naturally, the impact is universal.

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" +
    "");
}]);

Answer №2

Looking back at the response provided for this particular question on Stack Overflow, one suggestion is to encapsulate the outcomes within a div element and then specify the necessary width. As an example, the width of the div was set to 800px.

<div style="width:100%;">
    <span>{{showLinks}}</span> <!-- displays correctly -->
    <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">
      <div style="width:800px;">{{showLinks}}</div>
      <a>
        <span ng-bind-html="match.label | typeaheadHighlight:query"></span>
      </a>
    </script>
</div>

Answer №3

After some trial and error, I successfully got it to function by implementing a watcher on a variable linked to typeahead-is-open.

Within the directive template:

<input type="text" ng-model="asyncSelected" placeholder="Enter something" uib-typeahead="address for address in getLocation($viewValue)" typeahead-loading="loadingLocations" typeahead-no-results="noResults" typeahead-is-open="typeaheadIsOpen" class="form-control">
<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>
<div ng-show="noResults">
  <i class="glyphicon glyphicon-remove"></i> No Results Found
</div>

Within the directive controller:

$scope.$watch('typeaheadIsOpen', function(newVal, oldVal) {
  if (newVal == oldVal) {
    return;
  }
  if (newVal) {
    var searchField = angular.element.find('input');
    var width = searchField[0].offsetWidth;

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

Answer №4

.drp .dropdown-menu{
    left: 8px !important;
width: calc(100% - 15px);
  }
<div style="position: relative;" class="drp">
    <input type="text" ng-model="customSelected" placeholder="Custom template" uib-typeahead="state as state.Value for state in $ctrl.dimObj.Text | filter:{Value:$viewValue}" typeahead-template-url="customTemplate.html" class="form-control" >
    </div>

Adjusting AngularJS Typeahead Result Set Width to Match Input Size

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

the order of initialization in angularjs directives with templateUrl

In my current scenario, I am faced with a situation where I need to broadcast an event from one controller and have another directive's controller receive the message. The problem arises because the event is sent immediately upon startup of the contro ...

How to get the initial item from an API using JavaScript mapping

When mapping my arrays, I usually use the following code: moviesList.map(movie => <MovieCard movieID={movie} key={movie} However, there are instances where my API returns multiple results. Is there a way to modify my .map function to display only t ...

Struggling with your Dropdown Menu onclick functionality in Javascript? Let me lend

I am seeking assistance with implementing a Javascript onclick Dropdown Menu. The current issue I am facing is that when one menu is opened and another menu is clicked, the previous menu remains open. My desired solution is to have the previously open menu ...

Adding information to an HTML table using JQuery

Is there a way to incorporate JSON data into an HTML table? The JSON data follows this format: https://i.stack.imgur.com/lzdZg.png This is the desired HTML table structure: <table class="table table-bordered table-hover "> ...

How can you prevent videos from constantly reloading when the same source is used in multiple components or pages?

How can we enhance loading performance in Javascript, React, or Next JS when utilizing the same video resource across various components on different pages of the website to prevent unnecessary reloading? Is there a method to store loaded videos in memor ...

From where does useTranslate fetch the translations?

I have started my journey to learn React with NextJS and recently purchased this amazing template. While exploring the src/pages/terms.tsx file, I came across some quite complex code. One thing that intrigued me was the question: What does the ? in conten ...

Ways to analyze users who have clicked a button

After a user registers, they are automatically taken to /proto where they can view a list of animals available for adoption. However, the challenge lies in identifying the specific user who clicked the button (as this information must be associated with th ...

multer - the file uploaded by the request is not defined

I've been working on an app with Node, Express, and multer for image uploads. However, after submitting the form, req.file is coming up as undefined. I've spent hours trying to troubleshoot this issue but haven't been able to pinpoint the pr ...

I'm having trouble getting Stripe checkout to function properly with Angular 1.x

Utilizing the Stripe payment system for processing payments, I referenced a project on GitHub and a helpful blog. Incorporating nested views and routers in my project, the structure appears as follows: src app views controllers directives ...

Challenge with dynamic headers in nested Data Tables within Angular

I have integrated Angular DataTables into my application and I am attempting to build nested datatables with dynamic headers. Below is the HTML code snippet: <table datatable="ng" class="table table-striped table-bordered table-hover" dt-instance= ...

How can we convert milliseconds to the corresponding date and time zone in Java?

1)I am trying to determine the user's timezone and current time using the following code snippets: Calendar currentdate1 = Calendar.getInstance(); TimeZone tz = Calendar.getInstance().getTimeZone(); System.out.println("time zone"+tz); System.out.pri ...

React Native formInput Component with Underline Decoration

Utilizing the FormInput element in React Native Elements, I have observed a line underneath each FormInput component. Interestingly, one line appears fainter than the other. https://i.sstatic.net/ZD8CI.png This is how the form looks: <View style={sty ...

Leveraging redux within your NEXT.JS project

While working on my Next.js application, I have integrated Redux and Redux Saga. I am trying to incorporate server-side rendering for making HTTP requests: export const getStaticProps = wrapper.getStaticProps(async ({ store }) => { store.dispatch(g ...

Tips for including the % symbol in the Y-axis labels on a HighChart graph

https://i.sstatic.net/Ym7Uz.png I am attempting to incorporate the % symbol after the value of 100 or -100 on the yAxis in the chart shown above. I made an attempt to add the % symbols as follows: quotes.data.frequency_counts[i].negative = Math.round(ne ...

Refresh the HTML content within a specified div element

In my index.html, there is a graph (created using d3.js) along with some code that displays a stepper with a number of steps equal to the child nodes of the clicked node: <div ng-include="ctrl.numlab==2 && 'views/stepper-two-labs.htm ...

The image component is missing the necessary "src" attribute even though a valid src value has been provided as a prop

I'm encountering an issue in Next.JS where a component is not recognizing the image source passed through a prop. I am providing the path of an image named "logo.jpg" from the project's public folder. The image successfully displays when used as ...

Deactivate click events in the container div

Here is the html code snippet that I am working with: <div class="parent" ng-click="ParentClick()"> . . . <div class="child" ng-click="ChildClick()"> Some Text </div> </div> When clicking on Som ...

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...

Application initialized and ready to receive data results from REST calls

After working on a few basic web applications with Angular, I am still in the process of learning and exploring new things... My current goal is to develop an Angular application that relies on various parameters within the application. For instance, we w ...

Restrict the amount of displayed information in Vue

I'm having trouble creating a Vue button that limits the display of items fetched from an API. The goal is to only show 3 out of 10 questions initially, and when the "showmore" button is clicked, another set of 3 should be displayed, and so on. Howeve ...