简体   繁体   中英

Updating model value in Angular Bootstrap UI typeahead

I am using the Angular Bootstrap UI typeahead and trying to update the model value inside the typeahead . But the updated model value does not reflect the changes unless specifically applied.

<input ng-model="query" typeahead="option for option in getOptions($viewValue)">

app.controller('MainCtrl', function($scope) {
  $scope.query = '';
  $scope.getOptions = function(query){
    if(query == "foo"){
      $scope.query = "foobar";
      // uncommenting the next line works but also raises error
      // $scope.$apply()
      return []
    }
    return ["I have an idea", "I have new idea"];
  }
});

Plunker Code: http://plnkr.co/edit/pNxBMgeKYulLuk7DO0gB?p=preview

You can accomplish this by watching the value of $scope.query .

In the $watch , newValue and oldValue represent the value of $scope.query after and before it is changed, respectively.

$scope.$watch("query", function(newValue, oldValue){
  if (newValue !== oldValue) {
    if (newValue === "foo") {
      $scope.query = "foobar";
    }
  }
});

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

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