有条件地包括角度选择选项

时间:2013-09-13 14:50:54

标签: javascript select angularjs angularjs-directive

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

<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(加载控制器时和响应选择值时)

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

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

1 个答案:

答案 0 :(得分:0)

使用$templateCachefor循环替代:

&#13;
&#13;
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);
&#13;
<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>
&#13;
&#13;
&#13;

<强>参考