如何在AngularJS中动态更新视图

时间:2014-08-08 19:28:19

标签: javascript angularjs angularjs-ng-click ng-show

我有2个div元素如下所示,我想根据在点击锚元素时在控制器中调用的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;
  };

}]);

上面的代码不起作用,因为即使单击执行内容并显示B 锚点元素,状态仍为“A”。

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

修改

app.js

 //...

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

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

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

    })

 //...  

的index.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>

myView.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>

2 个答案:

答案 0 :(得分:4)

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

更改

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

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

<强> Demo

来自Doc: -

  

ngShow表达式 - 如果表达式是真实的,那么元素将分别显示或隐藏。

答案 1 :(得分:1)

你非常接近。它不起作用的原因是属性&#34; ng-show&#34;不需要&#34; {{&#34; &#34;}}&#34;工作的符号。

我刚刚构建了你的代码但是把它们关掉了,它正如你所描述的那样工作。

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