问题
http://plnkr.co/edit/fXo21LnphHZ3qWnuEMFt?p=preview
Right now, if you click anywhere outside of the input, the focusMe directive scope.$watch
will trigger and turn showingTagSearchInput
false.
This needs to 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;
}
The 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));
})
}
}
}])
回答1:
Remove the blur event from focusMe
directive which is hidding div on blur.
Instead of that call ng-click
event that will set showingTagSearchInput
to false & element will get 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;
};
Demo Plunkr
回答2:
The problem comes from focus-me directives that, when is not anymore focus, invert your variable.
See updated plunkr for a solution http://plnkr.co/edit/443rVbs2onbx96aq4eaf?p=preview
I have created a new variable, that is initiate here :
function quickSearchTags() {
vs.showingTagSearchInput = !vs.showingTagSearchInput;
vs.focusMe = true;
}
And your directive is called like that :
<input type="text"
focus-me="focusMe"
placeholder="search for a tag"
ng-model="tagSearchInput"
class="form-control">
来源:https://stackoverflow.com/questions/31125880/how-to-modify-this-directive-so-that-once-the-input-is-visible-it-wont-be-hid