AngularJS控制器无法正确显示/隐藏

时间:2017-07-31 15:31:29

标签: javascript html angularjs controller

我试图让内容在按钮点击时消失,然后在该按钮点击上显示一组新内容。我不能让这个工作。我评论了每个部分正在做什么。单击按钮时,第一部分不会消失。第二部分按预期工作, 在按钮点击时消失,第三部分不显示按钮点击。非常感谢帮助,我期待从中学习!

我想通过添加一个控制器,它将全部起作用。

HTML

<!-- THIS DOESN'T DISAPPEAR ON BUTTON CLICK -->
<div ng-controller="EventCtrl" ng-hide="eventComplete">
    <h2>Example that doesn't disappear on button click</h2>
</div>

<!-- THIS WILL DISAPPEAR ON BUTTON CLICK -->
<div ng-controller="EventCtrl" ng-hide="eventComplete"> 

    <div>
        <h2>Example</h2>
        <md-button ng-click="eventFinish();">Finish</md-button>
    </div>

    <!-- THIS DOESN'T SHOW ON BUTTON CLICK -->
    <div ng-controller="EventCtrl" ng-show="eventComplete">
        <h2>Complete!</h2>
    </div>
</div>

.controller('EventCtrl', function($rootScope,$state,$scope,$timeout){
  var self = this;
  $scope.eventComplete = false;
  $scope.eventFinish=function(){
    console.log('eventFinish'); //This logs
    $scope.eventComplete = true;
  };
})

2 个答案:

答案 0 :(得分:2)

您将要隐藏的div包裹在要显示的div周围。以下html应解决此问题:

.controller('EventCtrl', function($rootScope,$state,$scope,$timeout){
    var self = this;
    $scope.eventComplete = false;
    $scope.eventFinish = function() {
        console.log('eventFinish');
        $scope.eventComplete = true;
    };
})

编辑:在控制器中也发现了一个问题。你错过了eventFinish的结束}:

{{1}}

答案 1 :(得分:0)

尽量避免将相同的控制器放在彼此内。这只会导致问题。而是使用Components

但如果您坚持使用控制器,您可以通过这种方式解决问题。 (代码未经测试)

<强> HTML

<div ng-controller="EventCtrl"> 
    <div ng-if="showExample(1)">
        <h2>Example 1</h2>
        <md-button ng-click="onClickExample(2);">Finish</md-button>
    </div>

    <div ng-if="showExample(2)">>
        <h2>Example 2</h2>
        <md-button ng-click="onClickExample(1);">Finish</md-button>
    </div>
</div>

<强> JS

.controller('EventCtrl', function($rootScope,$state,$scope,$timeout){

  $scope.currentExample=1;

  $scope.showExample = function(id){
    return $scope.currentExample === id;
  }

  $scope.onClickExample = function(id){
    $scope.currentExample = id;
  } 
});
相关问题