Moving along in AngularJS, I get a JavaScript error on the // ERROR
line below.
Why do I get Cannot set property 'show' of undefined
?
<html ng-app>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js">
</script>
<div ng-controller='DeathrayMenuController'>
<button ng-click='toggleMenu()'>Toggle Menu</button>
<ul ng-show='menuState.show'>
<li ng-click='stun()'>Stun</li>
<li ng-click='disintegrate()'>Disintegrate</li>
<li ng-click='erase()'>Erase from history</li>
</ul>
<div/>
<script>
function DeathrayMenuController($scope) {
$scope.menuState.show = false; // ERROR HERE
$scope.toggleMenu = function() {
$scope.menuState.show = !$scope.menuState.show;
};
}
</script>
</body>
</html>
you never define $scope.menuState
. Instead consider:
<html ng-app>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-controller='DeathrayMenuController'>
<button ng-click='toggleMenu()'>Toggle Menu</button>
<ul ng-show='menuState_show'>
<li ng-click='stun()'>Stun</li>
<li ng-click='disintegrate()'>Disintegrate</li>
<li ng-click='erase()'>Erase from history</li>
</ul>
<div/>
<script>
function DeathrayMenuController($scope) {
$scope.menuState_show = false;
$scope.toggleMenu = function() {
$scope.menuState_show = !$scope.menuState_show;
};
}
</script>
</body>
</html>
Just working through the same book and came across this issue. Thought I'd add that the following works as well:
<html ng-app>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js">
</script>
<div ng-controller='DeathrayMenuController'>
<button ng-click='toggleMenu()'>Toggle Menu</button>
<ul ng-show='menuState.show'>
<li ng-click='stun()'>Stun</li>
<li ng-click='disintegrate()'>Disintegrate</li>
<li ng-click='erase()'>Erase from history</li>
</ul>
<div/>
<script>
function DeathrayMenuController($scope) {
$scope.menuState = {show: false}; // ERROR HERE
$scope.toggleMenu = function() {
$scope.menuState.show = !$scope.menuState.show;
};
}
</script>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With