动态自动完成指令

时间:2016-03-03 04:13:14

标签: javascript jquery angularjs jquery-ui autocomplete



我在自动完成angularjs指令传递的动态数据方面遇到了麻烦,该指令由jquery-ui自动完成组成。这是我目前的代码:

HTML:

ES

JS:

<div ng-app="peopleApp">
    <div ng-controller="indexController">
        <label class="input-group-addon input-label">Search:</label>
        <input class="form-control input-form" id="search" type="text" placeholder="Search here..." auto-complete names="names">
        <button ng-click="change()">Change</button>
    </div>
</div>

首先,从API获取的数据未集成在自动完成中。其次,我希望当按下按钮时,将更改的$ scope.names也将集成在自动完成中

1 个答案:

答案 0 :(得分:1)

使用jQuery autocomplete的工作解决方案。

jsfiddle上的实例。

&#13;
&#13;
function DefaultCtrl($scope) {
  $scope.names = ["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.addName = function() {
    $scope.names.push($scope.name);
  }
}

angular.module('MyModule', [])
.controller('DefaultCtrl',DefaultCtrl)
.directive('autoComplete', function($timeout) {
  return {
    restrict: "A",
    scope: {
      uiItems: "="
    },
    link: function(scope, iElement, iAttrs) {
      scope.$watchCollection('uiItems', function(val) {
        console.log(val);
        iElement.autocomplete({
          source: scope.uiItems,
          select: function() {
            $timeout(function() {
              iElement.trigger('input');
            }, 0);
          }
        });
      });

    }
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css"  rel="stylesheet" type="text/css">
<div ng-app='MyModule'>
  <div ng-controller='DefaultCtrl'>
    <input auto-complete ui-items="names" ng-model="selected"> selected = {{selected}}
    <br>
    <input placeholder="add name" ng-model="name">
    <button ng-click="addName()">
      Add name
    </button>
    <pre>{{names|json}}</pre>
  </div>
</div>
&#13;
&#13;
&#13;