1

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

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Jonathan, that works perfectly. I am still unable to understand why updating model inside getOptions() doesn't work, while $watch works?
One thing I can note is that there is no $scope.apply() method. However there is a $scope.$apply() which also cause an error of $apply already in progress.
Yeah, I missed the $. I was trying to avoid the $apply() thing.
I believe that it is changing the $scope.query to foobar successfully. However the typeahead is coming along and stomping all over that scope variable after is its changed in getOptions() Have a look here plnkr.co/edit/i2l0z5EIiUUujVhAlJig?p=preview, if you look in the console you will see getOptions fired, changing to foobar, value change: foo. Immediately after the changing to foobar message the value is changed back to foo. Most likely by the type ahead directive.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.