Reputation: 872
Why this code give error? I get error that "Cannot set property 'show' of undefined"
<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/>
function DeathrayMenuController($scope) {
$scope.menuState.show = false;
$scope.toggleMenu = function() {
$scope.menuState.show = !$scope.menuState.show;
};
// death ray functions left as exercise to reader
}
Upvotes: 0
Views: 109
Reputation: 3967
You're not defining $scope.menuStage first. Try this instead:
<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/>
function DeathrayMenuController($scope) {
$scope.menuState_show = false;
$scope.toggleMenu = function() {
$scope.menuState_show = !$scope.menuState_show;
};
// death ray functions left as exercise to reader
}
Upvotes: 0
Reputation: 101680
You can't set the show
property on $scope.menustate
if $scope.menustate
is undefined
. You need to initialize it first:
$scope.menuState = {};
$scope.menuState.show = false;
or alternatively:
$scope.menuState = {
show: false
};
Upvotes: 2
Reputation: 21901
you are going to assign a show
property to $scope.menuState
object but you don't have $scope.menuState
object,
so what u need to do is, create a $scope.menuState
object beginning of the controller as,
function DeathrayMenuController($scope) {
$scope.menuState = {}; // initialize the object first.
$scope.menuState.show = false;
$scope.toggleMenu = function() {
$scope.menuState.show = !$scope.menuState.show;
};
// death ray functions left as exercise to reader
}
Upvotes: 0