简体   繁体   中英

Cannot get typeahead-on-select working with Angular UI Bootstrap

See Plunker: http://plnkr.co/edit/hsxYC2KPsf7S3non34Cy .

HTML:

<input type="text" ng-model="result" typeahead="suggestion for suggestion in cities($viewValue)" typeahead-on-select="onSelect($item)">

JavaScript:

$scope.cities = function(cityName) {
    $scope.city = cityName.split(" ");
       // $timeout emulates an async call to a server.
       return $timeout(function() {
            switch ($scope.city[0]) {
                case 'N':
                    return {cand: ["New"]};
                case 'New':
                    return {cand: ["New Albany", "New York"]};
                default:
                    return {cand: ["<no match>"]};
            }
        }, 1000).then(function(res) {
            return res.cand;
        });
  };

  $scope.onSelect = function($item) {
      $scope.cities($item);
  };

Give 'N' as input, wait for 1 sec. The typehead list appears, select 'New' (State A). The list disappears, no new proposals. Press space, still no typeahead list.

Demonstration of the needed behaviour: Give 'New' as input. The typeahead list appears with 'New Albany' and 'New York' to select from. I want to see the same list in State A.

On typeahead-on-select with a true server, I am able to get the server to send the new list ('New Albany' and 'New York'), but the problem is that Angular just does not display the list.

After some fiddling, it looks like you need to set the $viewValue explicitly and let angular render it for you as it normally does like so:

$scope.onSelect = function($item) {
   var theInput = angular.element(document.querySelector('#theInput'));
    var ngModelCtrl = theInput.controller('ngModel');

    ngModelCtrl.$setViewValue($item);
    ngModelCtrl.$render();
};

This code could probably be improved quite a bit - currently, I'm having trouble getting the dropdown to STOP displaying. But it does what you want.

Plunkr here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM