实现这样的一个需求:点击某个按钮,然后显示或隐藏某块区域。
先注册一个AngularJS的一个module:
var myApp = angular.module("myApp",[]);
为module注册controller:
myApp.controller("MyController",[‘$scope‘,function($scope){$scope.menuState.show = false;$scope.toggleMenu = function(){$scope.menuState.show = !$scope.menuState.show;};}]);
以上,toggleMenu函数用来修改show字段的true或false,即toggle。
AugularJS为我们提供了一个ng-show,当为true就显示,反之不显示。
<div ng-controller="MyController"><button ng-click="toggleMenu()">Toggle Menu</button><ul ng-show="menuState.show"><li>aa</li><li>bb</li></ul></div>
运行,报错: TypeError: Cannot set property ‘show‘ of undefined
原来,show作为menuState的一个字段,而menuState作为对象还没有声明。加上声明menuState对象的代码:
myApp.controller("MyController",[‘$scope‘,function($scope){$scope.menuState={};$scope.menuState.show = false;$scope.toggleMenu = function(){$scope.menuState.show = !$scope.menuState.show;};}]);
完整如下:
<!doctype html><html ng-app="myApp"><head><meta charset="UTF-8"><title>Untitled Document</title><script src="angular.min.js"></script><script>var myApp = angular.module("myApp",[]);myApp.controller("MyController",[‘$scope‘,function($scope){$scope.menuState={};$scope.menuState.show = false;$scope.toggleMenu = function(){$scope.menuState.show = !$scope.menuState.show;};}]);</script></head><body><div ng-controller="MyController"><button ng-click="toggleMenu()">Toggle Menu</button><ul ng-show="menuState.show"><li>aa</li><li>bb</li></ul></div></body></html>
总结:
● ng-show:是否显示元素
● 对象一定要先声明或初始化
时间: 2024-10-30 13:51:02