How do I change this directive so that once the input is visible it won't be hidden unless x is pressed?
http://plnkr.co/edit/fXo21LnphHZ3qWnuEMFt?p=preview
Right now, if you click anywhere outside the input, the focusMe directive scope.$watch
will infer and turn showingTagSearchInput
false.
This should only happen when the close x button is clicked .
Markup
<div class="sidebar" ng-controller="sidebar">
<div class="btn-search"
ng-hide="showingTagSearchInput"
ng-click="quickSearchTags()">Search</div>
<div class="search-tags-input container-fluid" ng-show="showingTagSearchInput">
<input type="text"
focus-me="showingTagSearchInput"
placeholder="search for a tag"
ng-model="tagSearchInput"
class="form-control">
<div>close x</div>
</div>
</div>
Controller functions
// search button stuff:
function quickSearchTags() {
vs.showingTagSearchInput = !vs.showingTagSearchInput;
}
function closeMe() {
console.log('closeMe clicked');
vs.showingTagSearchInput = false;
}
FocusMe directive:
.directive('focusMe', ['$timeout', '$parse', function($timeout, $parse) {
return {
link: function(scope, element, attrs) {
var model = $parse(attrs.focusMe);
scope.$watch(model, function(value) {
console.log('value ', value);
console.log('element ', element);
if (value === true) {
$timeout(function() {
element[0].focus();
});
}
});
element.bind('blur', function() {
scope.$apply(model.assign(scope, false));
})
}
}
}])
source to share
Extract the blur event from the directive focusMe
that contains the markup div for blur.
Instead, it will call an ng-click
event that will set showingTagSearchInput
to false and the element will be hidden.
Markup
<input type="text"
focus-me="showingTagSearchInput"
placeholder="search for a tag"
ng-model="tagSearchInput"
class="form-control">
<div class="btn-close" ng-click="closeMe()">close x</div>
code
$scope.hideInput = function(){
$scope.showingTagSearchInput = false;
};
source to share
The problem comes from the focus-me directives which, when they no longer focus, invert your variable.
See updated plunkr for solution http://plnkr.co/edit/443rVbs2onbx96aq4eaf?p=preview
I created a new variable that starts here:
function quickSearchTags() {
vs.showingTagSearchInput = !vs.showingTagSearchInput;
vs.focusMe = true;
}
And your directive is called like this:
<input type="text"
focus-me="focusMe"
placeholder="search for a tag"
ng-model="tagSearchInput"
class="form-control">
source to share