Vivien Pipo Vivien Pipo - 4 months ago 33
AngularJS Question

How to update datalist for dynamic auto-completion?

I am using a datalist for having auto-completion in an input text.
I initialize it well, but I would like to update dynamically my source and my suggestions.

Do you know how to do something like this?

HTML:

<input type="text" ng-model="title" list="suggestionList" ng-change="changeIsRaised()">
<datalist id="suggestionList">
<option data-ng-repeat="ttl in titles" value="{{ttl}}">
</datalist>


JavaScript:

$scope.titles = ["Action Comics", "Detective Comics", "Superman", "Fantastic Four", "Amazing Spider-Man"];

$scope.changeIsRaised = function() {
if ($scope.title == "ch") {
var newSrc = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean", "paul", "pierre", "nicolas", "alfred", "gerard", "louis", "albert", "edouard", "benoit", "guillaume", "nicolas", "joseph"];
$scope.titles = newSrc;

}
}

Answer

You have 'nicolas' listed twice causing a ng-repeat error. You could add a track by $index to fix it, but probably you should just remove the duplicate.

function ctrl($scope) {
  $scope.titles = ["Action Comics", "Detective Comics", "Superman", "Fantastic Four", "Amazing Spider-Man"];

  $scope.changeIsRaised = function() {
    if ($scope.title == "ch") {
      var newSrc = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean", "paul", "pierre", "nicolas", "alfred", "gerard", "louis", "albert", "edouard", "benoit", "guillaume", "joseph"];
      $scope.titles = newSrc;

    }
  }
}
angular.module('app', []).controller('ctrl', ctrl);
<body ng-app="app">
  <div ng-controller="ctrl">
    <input type="text" ng-model="title" list="suggestionList" ng-change="changeIsRaised()">
    <datalist id="suggestionList">
      <option data-ng-repeat="ttl in titles" value="{{ttl}}">
    </datalist>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>

Comments