Programmatically triggering typeahead.js result display

后端 未结 17 1897
余生分开走
余生分开走 2020-11-30 05:01

I am using Twitter\'s typeahead.js (https://github.com/twitter/typeahead.js/) on an input field which is pre filled from a query string. After loading the page, i\'d like to

17条回答
  •  猫巷女王i
    2020-11-30 05:12

    The other answers were helpful but did not solve my problem. This solution does not involve customising any of the angular-ui code itself and serves the purpose of only triggering the typeahead to fetch results on an explicit button click.

    To do this I had to overlay a text field on top of another (disabled) text field that is the actual one with the typeahead. Nobody will know the other one is there but it needs to be there for angular-ui to launch the menu in the correct location. You can't make it a hidden field because it will not be able to show the menu in the correct location.

    The directive below will watch the typeaheadText and typeaheadTrigger variables to populate the disbled field when the button triggers this (by setting the trigger to true). The directive has isolated scope so it does not depend on anything other than passed in.

    directive('typeaheadTrigger', function() {
      return {
        require: ["ngModel"],
        scope: {
          typeaheadText: '=',
          triggerFlag: '='
        },
        link: function(scope, element, attr, ctrls) {
          scope.$watch('triggerFlag', function(value) {
            if (scope.triggerFlag) {
              ctrls[0].$setViewValue(scope.typeaheadText);
              scope.typeaheadText = '';
              scope.triggerFlag = false;
            }
          });
        }
      };
    })
    

    The controller sets a few things up for this - the trigger and text scope variables inside an object. This demonstrates how to do it - ideally you'd wrap this whole thing in another directive so it can be used in your application while hiding the details.

    Here's the plunk: http://plnkr.co/edit/UYjz6F5ydkMQznkZAlfx?p=preview

提交回复
热议问题