http://plnkr.co/edit/fXo21LnphHZ3qWnuEMFt?p=preview http://plnkr.co/edit/fXo21LnphHZ3qWnuEMFt?p=preview
现在,如果您单击输入之外的任何位置,则 focusMe 指令scope.$watch
将触发并转动showingTagSearchInput
false.
这仅需要在以下情况下发生:close x单击按钮。
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>
控制器功能
// 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));
})
}
}
}])