如何使用带有复选框的ng-show

时间:2015-09-14 19:16:55

标签: javascript angularjs checkbox

我已经尝试了所有可以找到的解决方案,但我被卡住了。我有2个复选框,HBO和Marvin。马文需要展示一个div。 HBO需要什么都不显示。它工作,直到我需要单击两次复选框才能显示/隐藏。通常这将是$ apply()问题,但似乎并非如此。我相信我没有正确更新模型。我忘了提到复选框需要在另一个为真时重置为false。 plunker

 var ctrl = this;
    ctrl.showMeMarvin = function () {
        if (ctrl.show === true) {
            //$timeout(function () {
            ctrl.marvin = false;
            ctrl.show = false;
            ctrl.hbo = false;
            //})
        }
        else {
            //$timeout(function () {
            ctrl.marvin = true;
            ctrl.show = true;
            ctrl.hbo = false;
            //})
        }
    };

    ctrl.showMeHBO = function () {
        if (ctrl.show === true) {
            // $timeout(function () {
            ctrl.show = false;
            ctrl.hbo = true;
            ctrl.marvin = false;
            //})
        }
        else {
            //$timeout(function () {
            ctrl.marvin = false;
            ctrl.hbo = true;
            //})
        }
    };

2 个答案:

答案 0 :(得分:2)

只需像这样更改div ng-show:

 <div class="col-xs-12" ng-show="checkedHBO == 1">

它可以在没有任何额外函数调用的情况下工作。

编辑: 要让它使用条件重置prev选择的值,您可以使用:

<div ng-controller="ShowController as ctrl">
  <div class="col-xs-12">
    <label for="checkedHBO" class="ts-label">HBO</label>
    <input id="checkedHBO" name="mygroup" type="radio" value="hbo"  ng-model="checkedHBO" ng-change="checkedMarvin = undefined"/>
    <label for="checkedMarvin" class="ts-label">Marvin</label>
    <input id="checkedMarvin" name="mygroup" type="radio" value="marvin" ng-model="checkedMarvin" ng-change="checkedHBO = undefined"/>
  </div>
  <div class="col-xs-12" ng-show="checkedHBO">
    <center>
      <div class="jumbotron">
                 DIV 1
                </div>
      <div class="jumbotron">
                  DIV 2
                </div>
      <div class="jumbotron">
                  DIV 3
                </div>
    </center>
  </div>
</div>

答案 1 :(得分:2)

您应该使用无线电输入而不是复选框。 http://plnkr.co/edit/hE68w9RKUoFamAWGgRzR?p=preview

<input name="radio" id="checkedHBO" type="radio"  ng-model="ctrl.show" ng-value="false" />
<input name="radio" id="checkedMarvin" type="radio" ng-model="ctrl.show" ng-value="true"/>
相关问题