Last active
May 13, 2017 15:13
-
-
Save iuliaL/a4d15abd7bbc232631b357b1ce8a6f91 to your computer and use it in GitHub Desktop.
typeahead directive angular es6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function typeaheadSearch() { | |
'ngInject'; | |
return { | |
restrict: 'AE', | |
scope: { | |
items: '=', | |
onInput: '&', | |
getQuestion: '&', | |
getQuestionsSet: '&', | |
loading: '=', | |
}, | |
link: function(scope, elem, attrs) { | |
scope.current = 0; | |
// showing which item is active | |
scope.$watch('items',function () { | |
if(!scope.items){ | |
return; | |
} | |
if(Object.keys(scope.items).length){ | |
scope.noResults = false; | |
const firstRes = scope.items[Object.keys(scope.items)[0]]; | |
scope.selectedItem = Object.keys(firstRes)[0]; // this is id | |
} else { | |
scope.noResults = true; | |
} | |
}); | |
scope.onQuestionSelection = function(selectedQuestion) { | |
scope.selected = true; | |
scope.getQuestion(selectedQuestion); | |
scope.reset(); | |
}; | |
scope.onCategorySelection = function(questions) { | |
scope.selected = true; | |
scope.getQuestionsSet(questions); | |
scope.reset(); | |
}; | |
scope.reset = function () { | |
//scope.current = 0; | |
scope.model = ''; | |
scope.selected = true; // hides the list initially | |
console.log('reset search'); | |
}; | |
scope.select = function () { | |
//console.log(scope.items) | |
if (scope.items) { | |
scope.onQuestionSelection({qId: scope.selectedItem}); | |
scope.reset(); | |
} | |
}; | |
elem.bind('keydown', function (evt) { | |
if ( scope.items == undefined ) { | |
return; | |
} | |
if (evt.which === 13 || evt.which === 9) { // 13- enter key | |
console.log('pressed Enter'); | |
scope.$apply(function () { | |
scope.select(); | |
}); | |
} else if (evt.which === 27) { // escape key | |
evt.stopPropagation(); | |
scope.$apply(function () { | |
scope.reset(); | |
}); | |
scope.$digest(); | |
} | |
}); | |
}, | |
templateUrl: 'directives/typeaheadSearch/typeaheadSearch.html' | |
} | |
} | |
export default { | |
name: 'typeaheadSearch', | |
fn: typeaheadSearch | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment