I am writing a Type-ahead / Autocomplete search with angular using directive and filter service. I am almost there but need your expert opinions on things which I am planning to achieve.
@Todos:
Look and feel
Allow navigation using keyboard
- Enter and Esc key handling
Could anyone review and suggest more optimize ways of writing this?
Also, shall I bind events within a parent controller scope or directive scope? Here is how my directive looks like:
var modServiceDef = angular.module('modSerDefinition', []);
modServiceDef.controller('modDefCtrl', ['$scope', 'myFactory', function($scope, myFactory) {
myFactory.getData().then(function (httpData) {
$scope.dataToPopulate = httpData;
},function(httpData) {
console.log('name retrieval failed.');
});
}
]);
modServiceDef.directive('typeAhead',[function() {
return {
scope : {
cinfo:'=datalist',
},
link:function(scope,element,attr) {
scope.visible = true;
scope.updateSearchTerm = function(selName) {
scope.sterm = selName;
}
},
templateUrl:'templates/typeahead.tmpl'
}
}]);
modServiceDef.factory('myFactory', function($http,$q) {
var factory = {};
var def = $q.defer();
factory.getData = function() {
$http.get('https://raw.githubusercontent.com/dominictarr/random-name/master/first-names.json')
.success(function(res){
factory.data = res;
def.resolve(res);
})
.error(function(err){
def.reject(err);
})
return def.promise;
}
return factory;
});
HTML:
<type-ahead datalist="dataToPopulate"></type-ahead>
Template:
<input type='search' id='idSearch' ng-model='sterm' placeholder='Enter Search Term' />
<ul ng-if='sterm.length'>
<a href='#'>
<li ng-model='selName' ng-click='updateSearchTerm(data)' ng-repeat="data in cinfo| filter:sterm as results track by $index " class='listdata'>
{{data}}
</li>
</a>
</ul>