我的下一个HTML代码包含ng-click
:
<div id="bl" ng-click="toggleBlock('photos')"></div>
<div class="item" ng-show="toggle == 'photos'"></div>
Angular JS:
$scope.toggleBlock = function (type) {
$scope.toggle = type;
}
默认情况下,隐藏块#bl
。
当我点击时,块.item
被打开。但是当我再次点击时,阻止不会被隐藏。
我如何切换元素?
我也试过了:
HTML:
ng-click="toggleBlock('photos')"
<div ng-show="toggle.photos"></div>
Angular JS:
$scope.toggle = {
'photos' : false
};
$scope.toggleBlock = function (type) {
$scope.toggle.type = ($scope.toggle.type) ? false : true;
}
答案 0 :(得分:0)
您可以将控制器中的布尔值更新为true
或false
然后将其绑定到要切换的元素的ng-show
。
这就是您的HTML的样子:
<div id="bl" class="btn btn-success" ng-click="toggleBlock()"></div>
<div class=" btn btn-info" ng-show="visible==true"></div>
,这就是您的控制器内部:
$scope.toggleBlock=function() {
$scope.visible = !$scope.visible;
}
答案 1 :(得分:0)
$scope.toggleBlock = function (type) {
$scope.toggle = ($scope.toggle === type) ? false : type;
}
长版本:
if($scope.toggle === type){ // your toggle already set to type
$scope.toggle = ''; // (or false) reset it's value, so ng-show="toggle == 'photos'" will fail and hide the element
}
else{ // $scope.toggle is not set or has another value, so we can assing type to it
$scope.toggle = type;
}
仅在您有多个命名块时才有用:
<div class="item" ng-show="toggle == 'photos'"></div>
<div class="item" ng-show="toggle == 'albums'"></div>
和多个命名切换,如果您正在使用sigle div照片 - 请考虑使用布尔值作为其他建议
答案 2 :(得分:0)
指令ng-show将评估displayPhotos并根据displayPhotos(真或假)显示它
并且toggleBlock将允许您切换true或false displayPhotos。
<div id="bl" ng-click="toggleBlock()"></div>
<div class="item" ng-show="displayPhotos"></div>
在你的controller.js中:
$scope.displayPhotos = false;
$scope.toggleBlock = function () {
$scope.displayPhotos = !$scope.displayPhotos;
}
答案 3 :(得分:0)
请检查可能是您想要这个 -
http://plnkr.co/edit/5vcJEZQri5TGQDuH51Sr?p=preview
在控制器中 -
$scope.toggle = false;
$scope.toggleBlock =function () {
$scope.toggle = !$scope.toggle;
}
HTML
<div id="bl" ng-click="toggleBlock()">Click me to see photo div: Photo</div>
<div class="item" ng-show="toggle">
Photo div
</div>
答案 4 :(得分:0)
至少你的切换功能应该是
$scope.toggleBlock = function (type) {
$scope.toggle[type] = !$scope.toggle[type];
}
&#13;