【问题标题】:AngularJS Controller Not Showing/Hiding CorrectlyAngularJS 控制器未正确显示/隐藏
【发布时间】:2017-07-31 15:31:29
【问题描述】:

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

我认为通过添加一个控制器,它可以一起运行。

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

【问题讨论】:

  • 您应该将所有的 html 包装在 &lt;div ng-controller="EventCtrl"&gt;&lt;/div&gt; 中,这样您就不必多次添加 ng-controller。

标签: javascript html angularjs controller


【解决方案1】:

您将要隐藏的 div 包裹在要显示的 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;
    };
})

【讨论】:

  • 这个答案非常完美,因为它得到了很好的解释,并为我当前的设置提供了一个合乎逻辑的解决方案。它还解决了多控制器问题,而无需以我目前的技能水平无法理解的方式重写我的代码。感谢您的帮助!
【解决方案2】:

尽量避免将相同的控制器放在彼此内部。那只会导致问题。而是使用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;
  } 
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 2015-11-30
    • 1970-01-01
    相关资源
    最近更新 更多