ng-selected不适用于ng-repeat设置默认值 [英] ng-selected does not work with ng-repeat to set default value
问题描述
我正在尝试设置选项的默认值 我正在使用select和ng-repeat.我确实在js文件中获取数据,并且调用了模型来在那里设置值.
I am trying to set default value of options I am using select and ng-repeat. I do get data in js file and I do call model to set value there.
请查看以下代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-ngrepeat-select-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="ngrepeatSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select ng-model="datamodel">
<option ng-repeat="dataitem in data"
ng-selected ="{{dataitem == datamodel}}">{{dataitem}}</option>
</select>
</form>
<hr>
<tt>repeatSelect = {{datamodel}}</tt><br/>
</div>
</body>
</html>
app.js文件
(function(angular) {
'use strict';
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = [1,2,3,4,5];
$scope.datamodel = 2;
}]);
})(window.angular);
这是我的朋克车
推荐答案
来自角度文档:
请注意,不带ngOptions使用的select指令的值为 总是一个字符串.当模型需要绑定到非字符串时 值,您必须使用指令将其显式转换(请参见 下面的示例)或使用ngOptions指定选项集.这是 因为option元素只能绑定到字符串值 礼物.
Note that the value of a select directive used without ngOptions is always a string. When the model needs to be bound to a non-string value, you must either explicitly convert it using a directive (see example below) or use ngOptions to specify the set of options. This is because an option element can only be bound to string values at present.
因此将$scope.datamodel = 2;
更改为$scope.datamodel = '2';
是可行的.请参阅更新的朋克车.
So changing $scope.datamodel = 2;
to $scope.datamodel = '2';
works. See updated plunker.
但是,最好改用ngOptions
.再次,从文档:
However, it's better to use ngOptions
instead. Again, from the docs:
在许多情况下,可以在
<option>
元素上使用ngRepeat而不是 ngOptions达到类似的结果.但是,ngOptions提供 一些好处,例如<select>
的模型具有更大的灵活性 通过选择分配为理解表达式的一部分,并且 另外,通过不创建内存来减少内存并提高速度 每个重复实例的新作用域.
In many cases, ngRepeat can be used on
<option>
elements instead of ngOptions to achieve a similar result. However, ngOptions provides some benefits, such as more flexibility in how the<select>
's model is assigned via the select as part of the comprehension expression, and additionally in reducing memory and increasing speed by not creating a new scope for each repeated instance.
因此,要将模型保持为整数,可以使用:
So to keep your model as an integer, you can rather use:
<select ng-model="datamodel" ng-options="dataitem for dataitem in data">
<option value="">Please Select</option>
</select>
请参见朋克车
这篇关于ng-selected不适用于ng-repeat设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!