Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot Set Property of Undefined Member

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>
like image 276
Kevin Meredith Avatar asked Jun 06 '13 01:06

Kevin Meredith


2 Answers

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>
like image 76
akonsu Avatar answered Sep 19 '22 14:09

akonsu


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>
like image 43
Chris Owens Avatar answered Sep 19 '22 14:09

Chris Owens