在AngularJS中移动,我在下面的// ERROR
行上收到了JavaScript错误。
为什么我会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>
答案 0 :(得分:10)
你永远不会定义$scope.menuState
。而是考虑:
<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>
答案 1 :(得分:9)
刚刚完成同一本书并遇到了这个问题。以为我会补充说以下内容也适用:
<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>
答案 2 :(得分:6)
勘误表显示了更正: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;
...