使用 AngularJS 和 ng-repeat 初始化选择 [英] Initializing select with AngularJS and ng-repeat
问题描述
我正在尝试使用 ng-repeat 和 AngularJS 1.1.5 来让选择框从预填充选项开始.相反,选择总是从没有选择任何内容开始.它还有一个我不想要的空选项.我认为没有选择任何东西会有副作用.
我可以使用 ng-options 而不是 ng-repeat 来完成这项工作,但我想在这种情况下使用 ng-repeat.虽然我的缩小示例没有显示它,但我也想设置每个选项的标题属性,据我所知,使用 ng-options 无法做到这一点.
我不认为这与常见的 AngularJs 范围/原型继承问题有关.至少我在 Batarang 检查时没有看到任何明显的东西.另外,当您使用 UI 在选择中选择一个选项时,模型会正确更新.
这是 HTML:
<div>运算符是:{{filterCondition.operator}}
<选择 ng-model="filterCondition.operator"><选项ng-repeat="运算符中的运算符"value="{{operator.value}}">{{operator.displayName}}</选项></选择>
还有 JavaScript:
function AppCtrl($scope) {$scope.filterCondition={运算符:'eq'}$scope.operators = [{值:'eq',显示名称:'等于'},{值:'neq',显示名称:'不等于'}]}
JS Fiddle 为此:http://jsfiddle.net/coverbeck/FxM3B/2/
好的.如果你不想使用正确的方式ng-options
,你可以添加ng-selected
属性和option
指令使预选工作.
I'm trying to get select-box to start off with a pre-filled option using ng-repeat with AngularJS 1.1.5. Instead the select always starts out with nothing selected. It also has an empty option, which I don't want. I think that there is a side effect of nothing being selected.
I can get this working using ng-options instead of ng-repeat, but I want to use ng-repeat for this case. Although my narrowed down example doesn't show it, I also want to set the title attribute of each option, and there is no way to do that using ng-options, as far as I know.
I don't think this is related to the common AngularJs scope/prototypical inheritance issue. At least I don't see anything obvious when inspecting in Batarang. Plus, when you pick an option in the select with the UI, the model does update correctly.
Here's the HTML:
<body ng-app ng-controller="AppCtrl">
<div>
Operator is: {{filterCondition.operator}}
</div>
<select ng-model="filterCondition.operator">
<option
ng-repeat="operator in operators"
value="{{operator.value}}"
>
{{operator.displayName}}
</option>
</select>
</body>
And the JavaScript:
function AppCtrl($scope) {
$scope.filterCondition={
operator: 'eq'
}
$scope.operators = [
{value: 'eq', displayName: 'equals'},
{value: 'neq', displayName: 'not equal'}
]
}
JS Fiddle for this : http://jsfiddle.net/coverbeck/FxM3B/2/
OK. If you don't want to use the correct way ng-options
, you can add ng-selected
attribute with a condition check logic for the option
directive to to make the pre-select work.
<select ng-model="filterCondition.operator">
<option ng-selected="{{operator.value == filterCondition.operator}}"
ng-repeat="operator in operators"
value="{{operator.value}}">
{{operator.displayName}}
</option>
</select>
这篇关于使用 AngularJS 和 ng-repeat 初始化选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!