6

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>
4

3 回答 3

10

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>
于 2013-06-06T01:57:23.927 回答
9

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>
于 2013-08-11T08:37:52.280 回答
6

The Errata shows the correction: http://oreilly.com/catalog/errata.csp?isbn=0636920028055

$scope.menuState.show = false; will give an undefined error 

Added $scope.menuState = {} before to fix the issue i.e.

function DeathrayMenuController($scope) {
  $scope.menuState = {} 
  $scope.menuState.show = false;
...
于 2013-08-15T23:33:50.080 回答