如何在AngularJS中动态更新视图

How to dynamically update view in AngularJS

本文关键字:动态 更新 新视图 AngularJS      更新时间:2023-09-26

我有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;
  };
}]);

上面的代码不起作用,因为即使在单击Do stuff并显示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>

正在更新作用域。但可能的问题是ng-show,你正在使用"{{notation}}"设置一个字符串,它总是成为真理(即使它是"真"或"假"),只是直接使用表达式。

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

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

从医生

: -

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

你很接近了。它不能工作的原因是属性"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>