2017-09-07 43 views
0

我似乎無法讓這個空白選項消失。有關如何做的建議? AngularJS沒有給我任何有用的信息,我嘗試了很多來自Stackoverflow的建議。這段代碼中出現了什麼是空白選項?

angular.module("myApp", []); 
 

 
angular.module("myApp").component("app", { 
 
    template: ` 
 
    <div> 
 
     <select 
 
     ng-model="$ctrl.foo" 
 
     ng-options="day.value as day.label for day in $ctrl.days track by day.value" 
 
     ></select> 
 
    </div> 
 
    `, 
 
    controller: function() { 
 
    this.days = _.range(0, 31).map(function(day) { 
 
     if (day === 0) return {label: "No Wait", value: day}; 
 
     return {label: "" + day, value: day}; 
 
    }); 
 
    this.foo = 2; 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 
 
<script src="https://code.angularjs.org/1.6.5/angular.js"></script> 
 

 
<body ng-app="myApp"> 
 
    <app></app> 
 
</body>

+0

不要以爲你可以擺脫它,請參閱[爲什麼AngularJS包括選擇空選項?](https://stackoverflow.com/questions/12654631/why-does-angularjs-include-an-empty-option-in-select) – user2718281

+1

更改'''this.foo = 2;'' 'to this'''this.foo = {value:2};''' –

+0

[爲什麼AngularJS在select中包含一個空選項?](https://stackoverflow.com/questions/12654631/why -does-angularjs-include-an-empty-option-in-select) –

回答

0

更改this.foo = 2;對象分配this.foo = { value: 2 };

+0

'''day.value as ...'在'ng-options'中使用,因此直接分配值應該可行。 – Icycool

+0

是的,我可以證實,'day.value'應該完美運作,我不希望整個對象回來,只有值。 –

0

好像卸下track by部分將解決這個問題

ng-options="day.value as day.label for day in $ctrl.days" 
+0

但是,這將強制在我的所有對象上存在'$$ hashKey',因爲所有對象都是基於'day.value'唯一的,所以我確實不需要它。 –

+0

[documentation]中有一個特定的部分(https ://docs.angularjs.org/api/ng/directive/ngOptions#-select-as-),也許可以有一些方法來實現它。 – Icycool

0

我解決了這個。我不能讓ng-options正常工作,但ng-repeatoptionng-value的伎倆:

angular.module("myApp", []); 
 

 
angular.module("myApp").component("app", { 
 
    template: ` 
 
    <div> 
 
     <select 
 
     ng-model="$ctrl.foo" 
 
     > 
 
     <option 
 
      ng-repeat="day in $ctrl.days track by day.value" 
 
      ng-value="day.value" 
 
     > 
 
      {{day.label}} 
 
     </option> 
 
     </select> 
 
    </div> 
 
    `, 
 
    controller: function() { 
 
    this.days = _.range(0, 31).map(function(day) { 
 
     if (day === 0) return {label: "No Wait", value: day}; 
 
     return {label: "" + day, value: day}; 
 
    }); 
 
    this.foo = 2; 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 
 
<script src="https://code.angularjs.org/1.6.5/angular.js"></script> 
 

 
<body ng-app="myApp"> 
 
    <app></app> 
 
</body>