AngularJS实现元素显示和隐藏的几个案例
AngularJS实现元素显示和隐藏的几个案例
发布时间:2016-12-30 来源:查字典编辑
摘要:案例一:控制html元素显示和隐藏有n种方法:html的hidden、css的display、jquery的hide()和show()、bo...

案例一:控制html元素显示和隐藏有n种方法:html的hidden、css的display、jquery的hide()和show()、bootstrap的.hide。今天的重点不是显示和隐藏,而是监听某个布尔变量值,自动改变元素显示和隐藏状态。监听函数、if判断、选择dom、设置dom,5行代码搞不定吧,而且毫无技术含量。

看代码:

<!DOCTYPE html> <html ng-app> <head> <meta charset="utf-8"> <title>ng-show and ng-hide directives</title> </head> <body> <div ng-controller="VisibleController"> <p ng-show="visible">字符串1</p> <p ng-hide="visible">字符串2</p> <button ng-click="toggle()">切换</button> </div> <script src="../lib/angularjs/1.2.26/angular.min.js"></script> <script> function VisibleController($scope) { $scope.visible = false; $scope.toggle = function () { $scope.visible = !$scope.visible; } } </script> </body> </html>

案例二:对于菜单、上下文敏感的工具以及很多其他情况来说,显示和隐藏元素是一项核心的功能。与Angualr中其他功能一样,Angular是通过修改数据模型的方式来驱动UI刷新,然后通过指令把变更反应到UI上。

ng-show和ng-hide这两条指令的功能是等价的,但是运行效果正好相反,我们都可以根据所传递的表达式来显示或隐藏元素。也就是说,ng-show在表达式为true时将会显示元素,为false时将会隐藏元素;而ng-hide则恰好相反。

这两条指令的工作原理是:根据实际情况把元素的样式设置为display:block来显示元素;设置为display:none来隐藏元素。

实例:

<html ng-app='myApp'> <head> <title>ng-show实例</title> </head> <body ng-controller='ShowController'> <button ng-click="toggleMenu()">Toggle Menu</button> <ul ng-show='menuState.show'> <li>Stun</li> <li>Disintegrate</li> <li>Erase from history</li> </ul> <script src="lib/angular/angular.js"></script> <script>var myApp=angular.module('myApp',[]) myApp.controller('ShowController', function($scope) {$scope.menuState={show: false}$scope.toggleMenu=function() {$scope.menuState.show=!$scope.menuState.show;}});</script> </body> </html>

运行结果:

AngularJS实现元素显示和隐藏的几个案例1

点击“Toggle Menu”按钮,效果如下:

AngularJS实现元素显示和隐藏的几个案例2

再次点击“Toggle Menu”按钮,下面的信息又隐藏了,交替变换。

案例三:

<!DOCTYPE html> <html ng-app="a2_12"> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="../js/angularJs-1.2.16-min.js"></script> <style type="text/css"> body{ font-size: 12px; } ul{ list-style-type: none; width: 408px; margin: 0px; padding: 0px; } div{ margin: 8px 0px; } </style> </head> <body> <div ng-controller="c2_12"> <div ng-show="{{isShow}}">脚本</div> <div ng-hide="{{isHide}}">1012@qq.con</div> <ul ng-switch on={{switch}}> <li ng-switch-when="1">11111111111111111</li> <li ng-switch-when="2">22222222222222222</li> <li ng-switch-default>33333333333333333</li> </ul> </div> <script type="text/javascript"> var a2_12 = angular.module('a2_12', []); a2_12.controller('c2_12', ['$scope', function($scope) { $scope.isShow=true; $scope.isHide=false; $scope.switch=2; }]); </script> </body> </html>

ng-switch指令的功能是显示匹配成功的元素,该指令需要结合ng-switch-when和ng-switch-default指令使用。

当指定的on值与某个或多个添加ng-switch-when指令的元素匹配时,这些元素显示,未匹配到的元素的隐藏。

如果没有找到与on值相匹配的元素时,则显示添加了ng-switch-default指令的元素。

以上就是为大家分享的三个AngularJS实现显示和隐藏的三个案例,希望对大家的学习有所帮助。

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类