在Angular Bootstrap UI typeahead中更新模型值

时间:2013-09-20 20:27:55

标签: angularjs angular-ui angular-ui-bootstrap

我正在使用Angular Bootstrap UI typeahead尝试更新typeahead 中的模型值。但是,除非特别应用,否则更新的模型值不会反映更改。

<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代码: http://plnkr.co/edit/pNxBMgeKYulLuk7DO0gB?p=preview

1 个答案:

答案 0 :(得分:1)

您可以通过观看$scope.query

的值来实现此目的

$watch中,newValueoldValue分别代表$scope.query之后和之前的值。

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

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