Skip to content

Instantly share code, notes, and snippets.

@m0sk1t
Created February 3, 2017 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m0sk1t/c831736b0b48e05497c41108e211bb98 to your computer and use it in GitHub Desktop.
Save m0sk1t/c831736b0b48e05497c41108e211bb98 to your computer and use it in GitHub Desktop.
MyAutocompleteDirective
<div ng-app="ExampleAutocomplete">
<div ng-controller="ExampleCtrl">
<my-autocomplete on-find="find(substr)" users="users">
</my-autocomplete>
</div>
</div>
angular.module('ExampleAutocomplete', [])
.factory('FakeAjax', function(){
var users = [
{ name: 'John' },
{ name: 'Joann' },
{ name: 'Jorge' },
{ name: 'Jack' },
{ name: 'Sara' },
];
String.prototype.tlc = String.prototype.toLowerCase;
return {
find: function(substr) {
return users.filter(function(el){return el.name.tlc().indexOf(substr.tlc()) !== -1;});
}
};
})
.directive('myAutocomplete', function(){
return {
restrict: 'E',
scope: {
users: '=',
onFind: '&'
},
transclude: true,
template: '<div ng-transclude><input type="text" ng-model="substr" ng-change="onFind({substr:substr})" /><br /><ul><li ng-repeat="u in users">{{u.name}}</li></ul></div>'
}
})
.controller('ExampleCtrl', ['$scope', 'FakeAjax', function($scope, FakeAjax){
$scope.users = [];
$scope.find = function(substr) {
$scope.users = FakeAjax.find(substr);
};
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
ul, li {
list-style-type: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment