问题描述
我使用AngularJS指令,我需要在我的模板设置下拉列表中选择的选项。
I am using AngularJS directive and I need to set a selected option of a dropdown list in my template.
<select id="energySource" ng-options="o.name for o in energyOptions" ng-model="energy" ng-selected="energy" ng-change="energyChange();"></select>
在optionlist的内容取决于资源由当页面加载的服务器发送。
The content of the optionlist depends on resources send by a server when the page is loaded.
var energyChosen = "All";
angular.element(document).ready(function () {
$.get('/Dashboard/GetResources', function (data) {
scope.Resources = data;
scope.energyOptions = [{ name: scope.Resources.Electricity, id: "Electricity" }, { name: scope.Resources.Gas, id: "Gas" },
{ name: scope.Resources.Water, id: "Water" }, { name: scope.Resources.Solar, id: "Solar" }];
scope.energy = scope.energyOptions[0];
energyChosen = scope.energy.id;
scope.$apply();
});
它的工作原理,只是一个空的选择是pselected $ P $它消失时,我选择一个选项
我希望能够preSELECT一个选项。我认为
It works except that a blank option is preselected which disappears when i select an optionI would like to be able to preselect one option. I thought that
scope.energy = scope.energyOptions[0];
会做的伎俩,但事实并非如此。我怎么能preSELECT一个选项,在这种情况下?
would do the trick but it didn't. How can i preselect an option in this case ?
推荐答案
你正在做你的 NG选项的方式
将选项的名称存储在 scope.energy
不整的选项。你这么做的时候,你在正确的轨道上:
The way you are doing your ng-options
it will store the name of the option in scope.energy
not the whole option. You were on the right track when you did:
scope.energy = scope.energyOptions[0];
但它不会工作,因为它预计scope.energy是名称,而不是整个选项。你想在你的 NG-选项
做的是一样的东西:
<select id="energySource" ng-options="o as on.name for o in energyOptions" ng-model="energy" ng-selected="energy" ng-change="energyChange();"></select>
重要的变化是增加了邻为o.name
。左边的O是将实际被选中并存储在你的 scope.energy
,而为o.name
是将你拉来向下显示的文本。
The important change is the addition of the o as o.name
. The 'o' on the left is what will actually be selected and stored in your scope.energy
, while the as o.name
is the text that will be displayed on your pull down.
这篇关于如何选择下拉列表angularjs一个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!