【问题标题】:How to make a <div> show only when a certain <select> dropdown option is selected? The <select> options are populated with the ng-repeat directive如何仅在选择某个<select> dropdown选项时显示<div>显示? <select> 选项使用 ng-repeat 指令填充
【发布时间】:2019-04-15 16:43:15
【问题描述】:

我有一个 select 下拉列表,其中填充了 angularjs ng-repeat 指令。我希望 div 仅在选择某个选项时显示。

代码如下:

<select type="text"
  class="form-control"
  ng-model="vm.request.requestType"  
  name="requestType" id="requestType"
  placeholder=""
  required>
   <option selected></option>
   <option value="test">test</option>
   <option ng-repeat="requestType in vm.requestTypes">{{requestType}}</option>
</select>

<script>
    $(function() {
      $("#requestType").change(function () {
        if ($("#test").is(":selected")) {
          $("#continueCheckbox").show();
        } else {
          $("#continueCheckbox").hide();
        }
      }).trigger('change');
    });
</script>

<div id="continueCheckbox">
  <input type="checkbox"
     name="continueCheckbox"
     value="continueCheckbox">
     Check this box to continue, and to confirm that you have read the 
     Documentation
</div>

“测试”选项仅用于测试功能是否有效。目前,无论选择什么,复选框都会显示,并且永远不会消失。

【问题讨论】:

  • 角度项目是你的吗?如果是这样,请不要使用 jQuery。请参阅下面的答案(和 cmets),了解使用 Angular 完成您想要的各种选项:ng-ifng-hideng-showng-class 和/或ng-style 都是做你想做的事情的潜在方法想要 Angular。
  • 您知道如何将数据从数据库中获取到您的 Angular 应用程序吗?

标签: javascript jquery html angularjs


【解决方案1】:

我强烈建议不要混合使用 AngularJS 和 jQuery。两者都是 DOM 操作框架,不能很好地协同工作。这是使用 AngularJS 完成目标的一种方法:

<div id="continueCheckbox" ng-if="vm.request.requestType === 'test'">
    <input type="checkbox"
           name="continueCheckbox"
           value="continueCheckbox">
        Check this box to continue, and to confirm that you have read the Documentation
</div>

【讨论】:

  • 非常重要:...不要混合 AngularJS 和 jQuery... - 在 Angular 项目中,您永远不需要使用 jQuery。如果你很想使用它,那么你就会错过一些关于“Angular 方式”的东西。另外,我是否可以建议提供ng-hideng-show 版本来实现这项工作? ng-if 具有与隐藏/显示不同的重要区别/用例。而且,好像这些选项还不够,甚至可以利用ng-styleng-class....
  • @cale_b 好电话,ng-hide 会更好地等效于 jQuery 的 .hide()
  • @Lex 这行得通!但是有一个问题,这似乎只有在复选框显示时才会改变,有没有办法让它在文本出现和消失的地方随之出现?编辑:没关系,我明白了。尝试使用不同的选项并刷新 ctrl+F5,它似乎工作正常
【解决方案2】:

您是否尝试过使用ng-class 指令?

<div id="continueCheckbox" ng-class="selected: vim.request.requestType === 'test'"></div>

然后处理.css文件中的样式

.selected {
  display: none;
}

【讨论】:

    【解决方案3】:

    如果你想使用 jQuery,你可以检查 select 的值。你已经设置好了。

    var selectType=$(this).val();
    if (selectType=="test") // instead of if ($("#test").is(":selected")) 
    

    您也可以使用带有 .value 的 vanilla JS 来进行比较。

    【讨论】:

      猜你喜欢
      • 2016-03-25
      • 2019-01-11
      • 2022-12-06
      • 1970-01-01
      • 2010-11-10
      • 2016-08-28
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多