Cha*_* O. 132 javascript angularjs
我正试图让选择框从使用Ang-repeat和AngularJS 1.1.5的预填充选项开始.相反,选择始终从未选择任何内容开始.它也有一个空选项,我不想要.我认为没有被选中的副作用.
我可以使用ng-options而不是ng-repeat来使用它,但我想在这种情况下使用ng-repeat.虽然我的缩小示例没有显示,但我也想设置每个选项的title属性,据我所知,使用ng-options无法做到这一点.
我不认为这与常见的AngularJs范围/原型继承问题有关.至少我在Batarang检查时没有看到任何明显的东西.此外,当您使用UI选择选项中的选项时,模型会更新正确.
这是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>
Run Code Online (Sandbox Code Playgroud)
和JavaScript:
function AppCtrl($scope) {
$scope.filterCondition={
operator: 'eq'
}
$scope.operators = [
{value: 'eq', displayName: 'equals'},
{value: 'neq', displayName: 'not equal'}
]
}
Run Code Online (Sandbox Code Playgroud)
zs2*_*020 224
好.如果您不想使用正确的方法ng-options,可以添加ng-selected带有option指令的条件检查逻辑的属性,以进行预选工作.
<select ng-model="filterCondition.operator">
<option ng-selected="{{operator.value == filterCondition.operator}}"
ng-repeat="operator in operators"
value="{{operator.value}}">
{{operator.displayName}}
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
Jer*_*ess 34
对于select标签,angular提供ng-options指令.它为您提供了设置选项和设置默认值的特定框架.这是使用ng-options的更新小提琴按预期工作:http://jsfiddle.net/FxM3B/4/
更新的HTML(代码保持不变)
<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.value as operator.displayName for operator in operators">
</select>
</body>
Run Code Online (Sandbox Code Playgroud)
感谢TheSharpieOne指出了ng-selected选项.如果这是作为答案而不是评论发布的,我会做出正确的答案.
这是一个有效的JSFiddle:http://jsfiddle.net/coverbeck/FxM3B/5/.
我还更新了小提琴,使用了我在原帖中遗漏的title属性,因为它不是问题的原因(但这是我想使用ng-repeat而不是ng-options的原因) .
HTML:
<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator}}</div>
<select ng-model="filterCondition.operator">
<option ng-repeat="operator in operators" title="{{operator.title}}" ng-selected="{{operator.value == filterCondition.operator}}" value="{{operator.value}}">{{operator.displayName}}</option>
</select>
</body>
Run Code Online (Sandbox Code Playgroud)
JS:
function AppCtrl($scope) {
$scope.filterCondition={
operator: 'eq'
}
$scope.operators = [
{value: 'eq', displayName: 'equals', title: 'The equals operator does blah, blah'},
{value: 'neq', displayName: 'not equal', title: 'The not equals operator does yada yada'}
]
}
Run Code Online (Sandbox Code Playgroud)
angular将空选项元素注入select的事实是默认绑定到它的模型对象在初始化时带有空值.
如果要选择默认选项,则可以在控制器的范围内进行设置
$scope.filterCondition.operator = "your value here";
Run Code Online (Sandbox Code Playgroud)
如果你想要一个空选项占位符,这对我有用
<select ng-model="filterCondition.operator" ng-options="operator.id as operator.name for operator in operators">
<option value="">Choose Operator</option>
</select>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
243756 次 |
| 最近记录: |