http://plnkr.co/edit/fXo21LnphHZ3qWnuEMFt?p=preview
现在,如果您单击输入框以外的任何地方,focusMe 指令 scope.$watch
将触发并将 showingTagSearchInput
变为 false。
这需要仅在单击关闭 x 按钮时发生。
标记
<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 函数
// search button stuff:
function quickSearchTags() {
vs.showingTagSearchInput = !vs.showingTagSearchInput;
}
function closeMe() {
console.log('closeMe clicked');
vs.showingTagSearchInput = false;
}
focusMe 指令:
.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));
})
}
}
}])
最佳答案
从 focusMe
指令中删除模糊事件,该指令在模糊时隐藏 div。
而不是调用 ng-click
事件将 showingTagSearchInput
设置为 false & 元素将被隐藏。
标记
<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>
代码
$scope.hideInput = function(){
$scope.showingTagSearchInput = false;
};
关于javascript - 如何修改此指令,以便一旦输入可见,除非单击 x,否则它不会被隐藏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31125880/