Open AngularUI Bootstrap Typeahead Matches Results via Controller

十年热恋 提交于 2019-12-11 07:14:22

问题


Is there anyway to trigger opening the match results on a typeahead input text box from the controller?

use case:

  • user goes to https://example.com/search/searchText
  • controller of page sets the input text to "searchText" (ng-model) on initialization
  • trigger showing the typeahead results from the controller

I can only seem to get the typeahead results, obviously, while typing in the input text box.


回答1:


I got it to work in a couple ways, but both require changes to ui-bootstrap. I suppose I could create a pull request but not sure if my particular use case is a common one.

1) Custom directive and calling UibTypeaheadController.scheduleSearchWithTimeout method on focus of input element.

Directive:

.directive("showSearchResultsOnFocus", function($stateParams) {
return {
    require: ['uibTypeahead', 'ngModel'],
    link: function (scope, element, attr, ctrls) {
        var typeaheadCtrl = ctrls[0];
        var modelCtrl = ctrls[1];

        element.bind('focus', function () {
            if (!$stateParams.search || !modelCtrl.$viewValue) return;
            typeaheadCtrl.exportScheduleSearchWithTimeout(modelCtrl.$viewValue);
        });
    }
}

Update to ui-bootstrap:

this.exportScheduleSearchWithTimeout = function(inputValue) {
  return scheduleSearchWithTimeout(inputValue);
};

Bad: Requires making the method public on controller. Only method available is the init method and scope is isolated. Not meant to call from outside controller.

2) Add new typeahead attribute to allow setting default value and show results on focus:

Update to ui-bootstrap:

var isAllowedDefaultOnFocus = originalScope.$eval(attrs.typeaheadAllowDefaultOnFocus) !== false;
originalScope.$watch(attrs.typeaheadAllowedDefaultOnFocus, function (newVal) {
  isAllowedDefaultOnFocus = newVal !== false;
});

element.bind('focus', function (evt) {
  hasFocus = true;
  // this was line before: if (minLength === 0 && !modelCtrl.$viewValue) {
  if ((minLength === 0 && !modelCtrl.$viewValue) || isAllowedDefaultOnFocus) {
    $timeout(function() {
      getMatchesAsync(modelCtrl.$viewValue, evt);
    }, 0);
  }
});

Bad: Pull Request to ui-bootstrap but change perhaps not a common use feature. Submitted a PR here: https://github.com/angular-ui/bootstrap/pull/6353 Not sure if will be merged or not but using fork until then.

Any other suggestions?

Versions Angular: 1.5.8, UIBS: 2.2.0, Bootstrap: 3.3.7



来源:https://stackoverflow.com/questions/41026831/open-angularui-bootstrap-typeahead-matches-results-via-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!