2017-07-31 57 views
1

我试图让内容在按钮单击时消失,然后在该按钮上单击显示一组新内容。我无法完成这项工作。我评论了每个部分正在做什么。第一部分没有按钮点击消失。第二款按预期工作,确实消失在按钮点击和第三款不会按钮点击显示。非常感谢帮助,我期待着从中学习!AngularJS控制器无法正确显示/隐藏

我想通过添加一个控制器它会一起工作。

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> 

ANGULAR

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

你应该换所有的HTML的''

,这样你就不用加NG-控制器多次。 –

回答

2

你包裹要隐藏各地要显示在div股利。下面的HTML应该可以解决问题:

<div ng-controller="EventCtrl"> 

    <div ng-hide="eventComplete"> 
     <h2>Example that doesn't disappear on button click</h2> 
    </div> 

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

    <div ng-show="eventComplete"> 
     <h2>Complete!</h2> 
    </div> 
</div> 

编辑:在控制器中也发现了一个问题。您错过了eventFinish的关闭}:

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

这个答案是完美的,因为它很好地解释了并提供了一个合理的解决方案,与我目前的设置。它也解决了多重控制器问题,而无需以我目前的技能水平无法理解的方式重写我的代码。我感谢帮助! – user5854648

+0

@ user5854648非常欢迎您! –

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; 
    } 
});