角度范围不会像预期那样影响ng-show

时间:2015-06-10 01:37:12

标签: javascript angularjs angularjs-scope

我对Angular.js范围有疑问。

首先,我是Angular的新手,我已经阅读了范围文档,并尽力了解它。我有一种感觉,我的问题与此类似: ng-show not binding as expected

然而,我的例子本质上更简单,我仍然不明白我错过了什么。

我的HTML非常简单,我有一个包装所有内容的控制器:

<div ng-controller="ApplicationFormController"></div>

在这里我有部分:

<div ng-controller="ApplicationFormController">
<button ng-click="previous()">previous</button>
<button ng-click="next()">previous</button>
<p> You are on section #1 </p>
    <div class="section1" ng-show="{{ section.id == 1 }}"> Section 1 </div>
    <div class="section2" ng-show="{{ section.id == 2 }}"> Section 2 </div>
    <div class="section3" ng-show="{{ section.id == 3 }}"> Section 3 </div>
</div>

如您所见,我打算在将该部分应用于控制器时显示该部分。

我的应用程序逻辑如下:

app.controller('ApplicationFormController', ['$scope', function($scope) {
    $scope.sections = sections;
    $scope.section = $scope.sections[0];

    $scope.next = function() {
        var index = $scope.sections.map(function(x){
            return x.id;
        }).indexOf($scope.section.id);

        $scope.section = $scope.sections[index+1];
    };
    $scope.previous = function() {
        var index = $scope.sections.map(function(x){
            return x.id;
        }).indexOf($scope.section.id);

        $scope.section = $scope.sections[index-1];
    };

}]);

sections数组如下:

var sections = [
    {
        id: 1,
        name: 'Section 1',
        steps: [
            {
                id: 1,
                name: 'Step 1',
            },
            {
                id: 2,
                name: 'Step 2',
            },
            {
                id: 3,
                name: 'Step 3',
            },
        ]
    },
    {
        id: 2,
        name: 'Section 2',
        steps: [
            {
                id: 1,
                name: 'Step 1',
            },
            {
                id: 2,
                name: 'Step 2',
            },
            {
                id: 3,
                name: 'Step 3',
            },
        ]
    }
];

非常简单的东西。

所以问题在于展示和隐藏。

当我触发它运行的下一个或上一个事件时,我可以看到这个,因为<p>标签使用适当的ID进行更新,例如:如果我按下,p标签将更新以反映:

按预期

<p>You are on section #2</p>

奇怪的是目前显示的部分没有更新。在这种情况下,第一部分将保持可见,而第二部分将保持隐藏状态。

什么阻止DOM更新以反映控制器的当前状态。

1 个答案:

答案 0 :(得分:4)

这是因为ng-showexpression时需要which a watch is set internally。但是您通过使用插值(boolean string)提供表达式的值({{)。因此,观看之后永远不会执行,因为scope.$watch(attr.ngShow,...)将评估scope['true/false']而不是您想要的实际表达。

变化:

   <div class="section1" ng-show="{{ section.id == 1 }}"> Section 1 </div>

   <div class="section1" ng-show="section.id == 1"> Section 1 </div>

以及其他人也是如此。