1

我有div以下 2 个元素,我想根据doStuff()单击锚元素时在控制器中调用的函数仅显示其中一个。

<div ng-controller='myController'>
    <div ng-show="{{states['currentState'] == 'A'}}">
        //displaying this div if the currentState is A
        <a ng-click="doStuff('B')">Do stuff and show B</a>
    </div>
    <div ng-show="{{states['currentState'] == 'B'}}">
        //displaying this div if the currentState is B
    </div>
</div>

以下是控制器代码:

myApp.controller('myController', ['$scope', function($scope) {

  var states = ['A', 'B'];
  $scope.states = states;
  $scope.states['currentState'] = $scope.states['currentState'] || 'A';

  $scope.doStuff = function(stateToShow) {
    //doing stuff
    $scope.states['currentState'] = stateToShow;
  };

}]);

上面的代码不起作用,因为即使在单击Do stuff and show B锚元素后,状态仍保持为“A”。

有人可以帮我理解为什么它不起作用吗?

编辑

应用程序.js

 //...

    .state('home', {
        url: '/',
        views: {

            '': { templateUrl: 'partials/index.html' },

            'myView@home': {
                templateUrl: 'partials/myView.html',
                controller: 'VehicleController'
            }
            //other named ui views
        }

    })

 //...  

索引.html

<div class="main">
    <div class="container">
        <div class="row margin-bottom-40">
            <div class="col-md-12 col-sm-12">
                <div class="content-page">
                    <div class="row">
                        <div ui-view="myView"></div>
                        <!-- other named ui-views -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

我的视图.html

<div ng-controller='myController'>
    <div ng-show="states['currentState'] == 'A'">
        //displaying this div if the currentState is A
        <a ng-click="doStuff('B')">Do stuff and show B</a>
    </div>
    <div ng-show="states['currentState'] == 'B'">
        //displaying this div if the currentState is B
    </div>
</div>
4

2 回答 2

4

它正在更新范围。但可能问题在于ng-show您通过使用"{{notation}}"它来设置一个字符串,它总是变得真实(即使它是“true”或“false”),只需直接使用表达式。

改变

 <div ng-show="{{states['currentState'] == 'A'}}">

 <div ng-show="states.currentState === 'A'">

演示

来自文档:-

ngShow 表达式 - 如果表达式为真,则元素分别显示或隐藏。

于 2014-08-08T19:38:20.010 回答
1

你很亲密。它不工作的原因是属性“ng-show”不需要“{{”“}}”符号来工作。

我刚刚构建了您的代码,但将它们关闭了,它正在按照您所描述的那样工作。

<div ng-show="states['currentState'] == 'A'">
    //displaying this div if the currentState is A
    <a ng-click="doStuff('B')">Do stuff and show B</a>
</div>
<div ng-show="states['currentState'] == 'B'">
    //displaying this div if the currentState is B
</div>
于 2014-08-08T19:39:38.880 回答