Can someone check if I'm on the right track?
Preamble: I've created a Typeahead class that fetches data and keeps it within itself. The class has the following structure:
- input: stores the search text.
- list: stores the results.
- change: a function triggered when input changes.
- cursor: a function to track the selected element.
The problem is, the code looks bulky when attaching all necessary properties to an input:
<input
type="text"
ng-model="myTa.input"
ng-change="myTa.change();"
ng-keyup="myTa.cursor()"
....
/>
I wanted a directive that would automatically attach required properties to an element using only the Typeahead instance. For example:
<input type="text" my-typeahead="myTa" />
Before proceeding, here are some points to note:
- I want the directive to be flexible and work with inputs, textareas, selects, and links without using template or templateUrl.
- I prefer using ng-model over attrs.$observe or scope.$watch for simplicity.
- New elements within the root element will compile naturally but not the parent itself.
Is the approach below appropriate:
angular
.module('myTypeaheadDirective', [])
.directive('myTypeahead', function($compile, $rootScope) {
return {
restrict: 'A',
scope: {
typeahead: '=myTypeahead'
},
compile: function() {
return {
pre: function precompile(scope, element, attrs) {
var installedAttribute = 'my-typeahead-installed';
if ( angular.isUndefined( element.attr( installedAttribute ) ) ) {
element.attr('ng-model', 'typeahead.input');
element.attr('ng-change', 'typeahead.change()');
element.attr( installedAttribute, true );
$compile(element)(scope.$parent);
}
}
}
}
}
});
Explanation:
The directive checks if it's already installed to avoid looping.
Additional directives can be added inside the condition.
Note the use of ng-model="typeahead.input" for isolated scope.
$compile service recompiles the element using the parent scope to access the original Typeahead instance.
Queries:
- Is this approach too simplistic?
- Are there better alternatives?
- Will recompiling affect performance?
- Any issues with accessing the parent scope this way?
Thank you for your time and insights :)