Skip to content

Instantly share code, notes, and snippets.

@allaud
Created April 18, 2013 11:26
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 allaud/5412027 to your computer and use it in GitHub Desktop.
Save allaud/5412027 to your computer and use it in GitHub Desktop.
Angular autocomplete example
/*
{{value | json}}
<al-autocomplete min-length="1" data="MyAutoList" type="text" nn-model="value" nn-field="name" placeholder="Поиск по архиву" class="search-query span4">
{{item.name}} of age {{item.age}}
</al-autocomplete>
*/
angular.module('st', []).directive('alAutocomplete', function($http, $compile, $timeout) {
return {
restrict: 'E',
replace: true,
transclude: true,
template: "<input ng-model='query' />",
scope: {
localModel:'=nnModel'
},
controller: function($scope, $element, $transclude) {
$transclude(function(clone) {
$scope.contents = clone.text();
});
},
link: function(scope, element, attrs) {
console.log(scope, element, attrs);
var body = angular.element(document.body);
var query = attrs.ngModel.split(".")[0];
var style = 'position:absolute;background:#fff;';
var tpl = '<ul style="' + style + '" ng-show="query.length>min_length && should_show">' +
'<li ng-click="select(item)" ng-repeat="item in list | filter: query">' +
scope.contents +
'</li></ul>';
scope.min_length = attrs.minLength;
scope.list = window[attrs.data];
scope.should_show = false;
scope.selected = "";
scope.select = function(item){
scope.query = item[attrs.nnField];
scope.localModel = item;
};
element.after($compile(tpl)(scope));
element.bind("blur", function(){
$timeout(function(){
scope.should_show = false;
scope.$apply();
}, 200);
});
element.bind("focus", function(){
scope.should_show = true;
scope.$apply();
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment