我们说我有一个搜索框,我希望在用户点击按钮后显示它。到目前为止一切顺利。
但我想添加另一个功能,当用户点击任何地方时,搜索框会消失
我怎么能用AngularJs做到这一点?
这是我的代码:
HTML
<button class="btn btn-info " ng-click="addStyle()" ><i class="fa fa-search"></i>
Search</button>
<input type="text" placeholder="Type" class="{{noneStyle}} {{visibleStyle}}">
Angular
app.controller("MainCtrl", function($scope,$http){
$scope.noneStyle = "noneVisible";
$scope.addStyle = function(){
$scope.noneStyle = "visibleStyle";
}
})
任何想法?
Thx提前
答案 0 :(得分:1)
我建议使用ng-if代替
app.controller("MainCtrl", function($scope,$http){
$scope.visible = true;
$scope.changeStatus = function(){
$scope.visible = !$scope.visible;
}
$scope.hideAll= function(){
$scope.visible=false;
}
})
HTML
<div class="well" ng-controller="MyController">
<button class="btn btn-primary" ng-disabled="checked" ng-click="changeStatus()" ng-blur="hideAll()">BUTTON</button>
<hr/>
{{visible}}
<input type="text" placeholder="Type" ng-if="visible">
</div>
查看此jsFiddle
尝试一下!
答案 1 :(得分:1)
使用ng-blur / ng-focus来实现这一目标。
我在这里展示了一个简单的代码。 http://jsfiddle.net/lookman/1Lp95or0/
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', function($scope) {
$scope.visible = true;
$scope.changeStatus = function(){
$scope.visible = !$scope.visible;
}
$scope.hideAll= function(){
$scope.visible=false;
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyController">
<button ng-disabled="checked"
ng-click="changeStatus()">Click to show/hide the input box</button>
<hr/>
<p>Current visible status: {{visible}}</p>
<input type="text" placeholder="Type" ng-show="visible" ng-blur="hideAll()">
</div>
</div>
&#13;
请注意,在此示例中,您需要先单击输入框,然后单击其他位置以隐藏它。我希望这就是你在寻找什么,这有帮助。
答案 2 :(得分:0)
当用户点击其他地方时,使用ng-blur
指令更新您的模型:
<button class="btn btn-info " ng-click="addStyle()" ng-blur="removeStyle()">
答案 3 :(得分:0)
您可以使用标准JavaScript执行此操作,在显示搜索框后注册事件侦听器,并在用户点击任何位置时立即取消注册:
$scope.addStyle = function()
{
$scope.noneStyle = "visibleStyle";
// register event listener
document.addEventListener("click", hideSearchBox);
}
function hideSearchBox()
{
// set style to hide search box
$scope.noneStyle = "noneVisible";
// unregister event listener
document.removeEventListener("click", hideSearchBox);
}
我不确定是否有更多的Anuglar方法。为此,您需要在文档级别注册一些内容,因为您希望在任何地方单击时隐藏搜索框。并且&#34;任何地方&#34;可能不是Angular根范围的注册位置。