【问题标题】:Conditionally including select options in angular有条件地包括角度中的选择选项
【发布时间】:2013-09-18 07:35:46
【问题描述】:

我正在使用角度选择指令。

<select
    ng-model="tune.rating"
    ng-options="opt.value as opt.label for opt in dropdowns.rating"
    ng-change="update()" >
    <option ng-if="tune.rating === -1" value="">-- rate tune --</option>
</select>

我希望仅在尚未给出评级但未应用 ng-if 时才包含默认选项(无论是在加载控制器时还是响应选择值时)

有什么方法可以让它工作。我不能有条件地将默认选项附加到 dropdowns.rating,因为每页有很多曲调,所有这些都可能被评级或未评级,并且所有这些都使用 dropdowns.rating 数组

注意:我不认为我的问题与angularjs Select with filter to filter out the option that's already selected 重复,尽管它们相似

【问题讨论】:

  • 确保您使用至少 1.1.5 版来使用ng-if
  • @CodeHater 好地方。我已经升级了,现在可以使用了。
  • 你也可以使用 ng-hide/ng-show。
  • @ZackArgyle - 我不认为他们在选项上工作,因为他们依赖 css,我认为这不能应用于选项,角度 js 与否

标签: javascript select angularjs angularjs-directive


【解决方案1】:

使用$templateCachefor 循环作为替代:

var app = angular.module('foo', []);

function foo($templateCache)
  {
  var tmpl, lister,
  ProductData = 
    { "odata.metadata": "localhost:51811/odata/$metadata#Products", 
    "value": [
               {
               "ID": 1,
               "Year": 2017, 
               "Name": "Hat", 
               "Price": "15.00", 
               "Category": "Apparel" 
               }
             ]
    };

  lister = function()
  	{
    var index, replacement = "";
    for (index in this)
      {
      /* Avoid adding the callback function itself to the array */
      if (/[^\d]/.test(this[index]) === false)
        {
        replacement = replacement.concat("<option>",this[index],"</option>");
        }
      }
    return replacement;
    };
    
  ProductData.value[0].toJSON = lister;
  tmpl = JSON.stringify(ProductData.value[0]);
  
  console.log(tmpl);
    
  $templateCache.put('listContent', tmpl);
  }

app.run(foo);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="foo">
  <select ng-include="'listContent'"></select>
</div>

参考文献

【讨论】:

  • 我不确定这段代码应该做什么,但它似乎并不适用于这个问题。它似乎只为number 元素创建选项,而不为string 元素创建选项,这并不能真正解决问题。问题是当ng-model 没有值时如何只显示“默认”选项。
  • 这只是根据标题Conditionally including select options in angular 的一种方式。由于您的具体问题已通过升级解决,因此我没有在这里解决。
  • 这不是我的问题;感觉这个答案确实与问题主体脱节,并且是对一个已有 4 年历史的问题的奇怪补充。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-19
  • 1970-01-01
  • 2018-12-12
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多