I'm currently working on creating a custom directive for a small input field that only accepts text. The goal is to dynamically change an icon from a search glass to an X if there is text in the input field, and clear the text when it is clicked on. I have added the necessary HTML code to the input field, but I am struggling to get the native ng directive to function correctly. As I am relatively new to Angular, I am hoping that someone can offer assistance. While I have found some similar questions online, none of the solutions provided have fully resolved my issue.
angular.module('myApp')
.directive('searchBox', function ($compile) {
return {
restrict: 'A',
scope: {
ngModel: '='
}
link: function(scope, element, attrs) {
var appendix = angular.element(
'<span class="input-group-addon" ng-click="ngModel = none">' +
' <i ng-hide="ng-model" class="fa fa-search"></i>' +
' <i ng-show="ng-model" class="fa fa-close"></i>' +
'</span>');
var wrapper = angular.element(
'<div class="input-group input-group-sm search-box-custom"></div>'
);
element
.wrap(wrapper)
.after(appendix);
element.removeAttr("search-box"); //prevent endless compile loop
element.removeAttr("data-search-box"); //prevent endless compile loop*/
$compile(appendix)(scope);
}
};
});
The ng-model is specified within the input field
<input search-box
type="text"
ng-model-options="{debounce:1000}"
ng-model="inputValue"
placeholder="Hier Tippen..." />
Edit: The directive should have its own scope that is connected to the parent scope, but separate as the parent value may vary in different contexts.