bootstrap icon indicating copy to clipboard operation
bootstrap copied to clipboard

Trigger typeahead manually? Is that possible?

Open artworkad opened this issue 13 years ago • 34 comments

In my app the user may send a request for his position. When the position information is retrieved the data is populated to an input field which has the typeahead directive

document.getElementById('city').value = input;

But I want the typeahead to start and to search if the city is available in the typeahead resource. Is this possible?

artworkad avatar Aug 05 '13 09:08 artworkad

Nope, there is no such functionality as part of the typeahead directive. But what you could do is to write a very simple directive that would listen to model changes and call modelCtrl.$setViewValue() - this would open typeahead's suggestions.

Going to close this one for now as I don't think it is generic enough to be built in inside the typeahead's directive and - at the same time - it is very easy to achieve in a custom directive.

pkozlowski-opensource avatar Aug 05 '13 11:08 pkozlowski-opensource

@pkozlowski-opensource can you provide sample code? What is modelCtrl?

artworkad avatar Aug 07 '13 05:08 artworkad

he's talking about a directive that requires ngModel:

.directive(...)
    return {
        ...
        require: 'ngModel',
        ...

That would inject ngModel into the directive function as the 4th argument.

hallister avatar Aug 07 '13 05:08 hallister

I have a similar issue. I try to open the suggestions on input focus.

myapp.directive('typeaheadOpenOnFocus', function () {
    return {
        require: ['ngModel'],
        link: function (scope, element, attr, ctrls) {
            element.bind('focus', function () {     
                ctrls[0].$setViewValue();
                //ctrls[0].$render();
            });
        }
    };
})

It is just not working at all. I tried giving a string into $setViewValue parameter but nothing happened either...

cindoum avatar Sep 25 '13 19:09 cindoum

@cindoum,

module.directive("typeaheadWatchChanges", function() {
  return {
    require: ["ngModel"],
    link: function(scope, element, attr, ctrls) {
      scope.$watch('thing', function(value) {
        ctrls[0].$setViewValue(value);
      });
    }
  };
});

braco avatar Oct 14 '13 20:10 braco

Hi

Thanks for the directive.

2013/10/14 braco [email protected]

@cindoum https://github.com/cindoum,

module.directive("typeaheadWatchChanges", function() { return { require: ["ngModel"], link: function(scope, element, attr, ctrls) { scope.$watch('thing', function(value) { ctrls[0].$setViewValue(value); }); } }; });

— Reply to this email directly or view it on GitHubhttps://github.com/angular-ui/bootstrap/issues/759#issuecomment-26286040 .

cindoum avatar Oct 15 '13 12:10 cindoum

Would this work on a button click also? I got it to work on a 2nd input to trigger typeahead on the first input. But what I really need is for it to be triggered from the buttons. http://plnkr.co/edit/sZ2y2paigGMxdDDqSLje?p=preview

sonicparke avatar Oct 17 '13 19:10 sonicparke

I ran into this issue too. It will be very helpful if a typeahead directive will expose some public api to the scope with open/close methods, and we need and ability to disable automatic typeahead kick-in in this case.

zgmnkv avatar Nov 11 '13 14:11 zgmnkv

I've copied the typeahead directive code into a new directive called my-typeahead and included the following code in the end of the directive:

var openClickHandler = function (evt) {
    if (scope.matches.length < 1) {
        evt.stopPropagation();
    }
    modelCtrl.$setViewValue(' ');
    scope.$digest();
};

$(element).parent().find('.typeaheadTrigger').bind('click', openClickHandler);

That way, your typeahead element may be enclosed by a parent element and a trigger to the typeahead can be added anywhere within that parent element. Example:

<div class="input-group">
    <input ng-model="model" type="text" class="form-control" 
        my-typeahead="product.name for product in products" typeahead-min-length="0" />
    <span class="input-group-btn">
        <button type="button" class="btn btn-default typeaheadTrigger">
            &nbsp;<span class="caret"></span>&nbsp;
        </button>
    </span>
</div>

Not really sure if this is a good solution though...

andreflourenco avatar Mar 12 '14 19:03 andreflourenco

Hi i was struggeling all last week to get this thing working for me none actually worked until i found this plunker http://plnkr.co/edit/pFsPx0lTM7OZVwF97m1l?p=preview

it is using typeahead-input-formatter as suggested by one of the main contributers of angular typeahead ( i guess) here https://github.com/angular-ui/bootstrap/issues/981

reposting it here cause maybe in future someone like may self will be comming back for few days to this page looking and analyzing comments and suggestions to find a solution

ali4ever4 avatar Apr 13 '14 08:04 ali4ever4

@sonicparke @ArtworkAD I've tracked down precisely what is causing this. As such, this works:

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

The dismissClickHandler is basically wiping out any matches caused by clicking a button, because the logic says 'if there is a click that is not within the typeahead input, clear out the matches'. All I did (on line 3236 of typeahead.js) was comment out the bind to click, and it works, at least. It acts wonky b/c you have to click it a couple times to get it to dismiss.

As such, the way in which the click event is handled (let me preface this with this: I am not good at javascript) should be refactored to handle only calling dismissClickHandler when a click occurs in the popup (an entry is selected) which would result in the intended outcome (removing the popup). I suppose, though, that lots of edge cases would push one to say that, for example, the popup should also be dismissed when someone clicks away from the popup (for example, in a blank area). Perhaps, then, there is a way to say that 'if a element has a ng-click directive, don't dismiss it' but that feels wrong.

@pkozlowski-opensource, considering that the dismissClickHandler is causing this behavior (what @sonicparke is talking about) for any elements that exercise a click event (and correctly update the $setViewValue() thru a custom directive), should this case be reopened?

randywallace avatar Apr 30 '14 11:04 randywallace

FYI: You can trigger the opening of suggestions from anywhere like this (preferably in a related directive)

var ngModelCtrl = $element.find('input').controller('ngModel');
        ngModelCtrl.$setViewValue(' ');

kennethlynne avatar Aug 20 '14 10:08 kennethlynne

Hi, I've just wasted a couple of hours of my life trying to make the above suggestions work, without any luck. However, I did come up with a simple, though very inelegant, hack, and I'm posting it in case someone else finds it useful. Find the original definition of dismissClickHandler (line 3715 of the version I'm using, ui-bootstrap-tpls-0.11.0.js), and change it from this:

var dismissClickHandler = function (evt) {
       if (element[0] !== evt.target) {
            resetMatches();
            scope.$digest();
        } 
};

to this:

var dismissClickHandler = function (evt) {
    if (element[0] !== evt.target) {
        resetMatches();
        scope.$digest();
    } else if (element.val().length) {
        element.focus();
        hasFocus = true;
        getMatchesAsync(element.val());
    }
};

kazeno avatar Sep 01 '14 10:09 kazeno

I wanted to get the typeahead to trigger manually only on a button press by hiding the field with the typeahead behind another text field. No guarantees for how many browsers it works in, but tested in Chrome, FF, IE10 - I only need to support Chrome for my use ;-). Hope it helps the next person out: http://plnkr.co/edit/UYjz6F5ydkMQznkZAlfx?p=preview

mbyrne00 avatar Oct 09 '14 04:10 mbyrne00

Hello, this is a nice workaround https://github.com/angular-ui/bootstrap/issues/764#issuecomment-49098720

jossemarGT avatar Dec 12 '14 03:12 jossemarGT

focus event was a overhead for me, and i used click event - because focus occurred also after selection.. (i also overloaded the 'typeahead' directive itself)

app.directive('typeahead', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ctrl) {
            element.bind('click', function () {
                ctrl.$setViewValue();
            });
        }
    };
});

segevofer avatar Feb 17 '15 10:02 segevofer

I tried above but could not make it work. And even the plunker examples provided not working.

jbmyid avatar Apr 01 '15 08:04 jbmyid

For everyone having the same issue, the following example works for me.

angular.module('app').directive('typeahead', typeaheadWatchChanges);

  typeaheadWatchChanges.$inject = ["$timeout"];

  function typeaheadWatchChanges($timeout) {
    return {
      require: "ngModel",
      link: function (scope, element, attr, controller) {
        scope.$watch('vm.model', function (value) {
          if (value) {
            element.focus();
            var old = controller.$viewValue;
            controller.$setViewValue('');
            $timeout(function () {
              controller.$setViewValue(old);
            });
          }
        });
      }
    };
  }

robbse avatar Apr 14 '15 14:04 robbse

I finally got this working after quite a bit of hassle with the aforementioned proposed solutions. These were the scenarios that I had to have this working for:

  • user clicks inside input to trigger opening of dropdown for:
    • existing values on model
    • when model is undefined/blank
    • when existing model value is a number

Sorry this is in Coffeescript.... should be self explanatory however.

.directive 'typeaheadClickOpen', ($parse, $timeout)->
    dir =
        restrict: 'A'
        require: 'ngModel'
        link: ($scope, elem, attrs)->

            triggerFunc = (evt)->
                ctrl = elem.controller 'ngModel'
                prev = ctrl.$modelValue || ''
                ctrl.$setViewValue if prev then '' else ' '
                if prev then $timeout -> ctrl.$setViewValue "#{prev}"

            elem.bind 'click', triggerFunc

In order to trigger the dropdown when the value was blank/undefined I set to an empty space ' ' as the UI renders blank/undefined as '' already. It's not ideal because ' ' != '' and not sure how that would present in validation cases.

Another thing to note is for those model values that were numbers, I had to cast the prev values as a string ergo the "#{prev}" bit on the timeout.

It's disappointing to see such a huge need for exposing an API of sorts to trigger the dropdown and after nearly 2 years there is still no library solution.

jusopi avatar Jun 05 '15 19:06 jusopi

@jusopi thanks worked for me :+1:

jbmyid avatar Jul 03 '15 06:07 jbmyid