为什么对象上的`.show`属性会搞砸基于该对象的数据绑定?

时间:2014-12-17 17:40:35

标签: javascript angularjs data-binding show

非常新手的问题:

我正在编写一个片段,如果单击一个按钮,它可以显示和隐藏菜单。对menuState变量的数据绑定在以下代码中不起作用,其中我将.show属性标记为菜单状态。

<html ng-app>
<body>
<div ng-controller="DeathrayController">
    <p>menuState: {{menuState.show}}</p>
    <button ng-click="toggleMenu()">Toggle Menu</button>
    <ul ng-show='menuState.show'>
        <li >Stun</li>
        <li >Disintegrate</li>
    </ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>

<script>


function DeathrayController($scope){
    $scope.menuState.show = false;
    $scope.toggleMenu = function(){
        $scope.menuState.show = !$scope.menuState.show;
    };
}

</script>

但是,这段代码在menuState变量上没有.show属性就可以了:

<html ng-app>
<body>
    <div ng-controller="DeathrayController">
        <p>menuState: {{menuState}}</p>
        <button ng-click="toggleMenu()">Toggle Menu</button>
        <ul ng-show='menuState'>
            <li >Stun</li>
            <li >Disintegrate</li>
        </ul>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>

    <script>
    function DeathrayController($scope){
        $scope.menuState = false;

        $scope.toggleMenu = function(){
            $scope.menuState = !$scope.menuState;
        };
    }

    </script>
</body>
</html>

为什么.show属性搞砸了数据绑定?

更新: 这是我从控制台获得的错误消息:

TypeError: Cannot set property 'show' of undefined
    at new DeathrayController (file:///var/folders/61/3h5pq5d14sx9ry5mdgxt00480000gn/T/tmpyxin9v.htm:18:25)
    at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:27:325)
    at Object.instantiate (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:27:455)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:50:239
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:42:154
    at m (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:6:312)
    at k (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:42:16)
    at e (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:38:198)
    at e (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:38:215)
    at e (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:38:215)

但是为什么在没有menuState属性的情况下定义show

1 个答案:

答案 0 :(得分:1)

问题在于你无法声明这样的对象:

$scope.menuState.show = false;

因为之前未定义$scope.menuState,javascript尝试访问show的属性$scope.menuState并引发错误,您需要将代码更改为:

$scope.menuState = {show : false};