选项在 ng-repeat 时如何初始化 select 值?
How to initialize a select value when option is in ng-repeat?
起初我试过<select name='size' ng-model='sid' ng-options='y.id as y.title for y in arr'>
。但是提交表单时,发布的变量 size
不是 id 472 473 474
而是索引 0 1 2
.
然后我试了ng-options='y.title for y in arr track by y.id'
。但是选择的型号 sid
不是 473
而是 {"id":473,"title":"bb"}
所以我不能让 ng-init='sid = 473'
默认 473 项。
最后,我不得不使用 option ng-repeat='y in arr'
如下。但似乎 ng-init 没有用,因为它会在选项重复之前进行初始化。我怎样才能让它发挥作用?
谢谢。
<div ng-controller="Ctrl">
<select ng-model='sid' ng-init='sid = 473'>
<option ng-repeat='y in arr' value='{{ y.id }}'>
{{ y.id+' - '+y.title }}
</option>
</select>
{{ sid }}
<button ng-click='sid=474'>change to 474</button>
</div>
<script>
var app =angular.module('app', []);
function Ctrl($scope){
$scope.arr = [{"id":472,"title":"aa"},{"id":473,"title":"bb"},{"id":474,"title":"cc"}];
}
</script>
记得阅读文档:
"Do not use select as and track by in the same expression. They are not designed to work together." https://docs.angularjs.org/api/ng/directive/ngOptions
您只需要修复您的 ng-options:
<div ng-controller="Ctrl">
<select ng-init="sid = 473" ng-model='sid'
ng-options="y.id as ( y.id + ' - ' + y.title) for y in arr">
</select>
<input type="hidden" name="size" value="{{sid}}"/>
{{ sid }}
<button ng-click='sid=474'>change to 474</button>
</div>
使用不可见输入<input name="profile_id" type="text" style="margin-left:-10000px;" ng-model="profile"/>
我找到了解决方案,但并不理想。欢迎大家有好的想法分享。
起初我试过<select name='size' ng-model='sid' ng-options='y.id as y.title for y in arr'>
。但是提交表单时,发布的变量 size
不是 id 472 473 474
而是索引 0 1 2
.
然后我试了ng-options='y.title for y in arr track by y.id'
。但是选择的型号 sid
不是 473
而是 {"id":473,"title":"bb"}
所以我不能让 ng-init='sid = 473'
默认 473 项。
最后,我不得不使用 option ng-repeat='y in arr'
如下。但似乎 ng-init 没有用,因为它会在选项重复之前进行初始化。我怎样才能让它发挥作用?
谢谢。
<div ng-controller="Ctrl">
<select ng-model='sid' ng-init='sid = 473'>
<option ng-repeat='y in arr' value='{{ y.id }}'>
{{ y.id+' - '+y.title }}
</option>
</select>
{{ sid }}
<button ng-click='sid=474'>change to 474</button>
</div>
<script>
var app =angular.module('app', []);
function Ctrl($scope){
$scope.arr = [{"id":472,"title":"aa"},{"id":473,"title":"bb"},{"id":474,"title":"cc"}];
}
</script>
记得阅读文档:
"Do not use select as and track by in the same expression. They are not designed to work together." https://docs.angularjs.org/api/ng/directive/ngOptions
您只需要修复您的 ng-options:
<div ng-controller="Ctrl">
<select ng-init="sid = 473" ng-model='sid'
ng-options="y.id as ( y.id + ' - ' + y.title) for y in arr">
</select>
<input type="hidden" name="size" value="{{sid}}"/>
{{ sid }}
<button ng-click='sid=474'>change to 474</button>
</div>
使用不可见输入<input name="profile_id" type="text" style="margin-left:-10000px;" ng-model="profile"/>
我找到了解决方案,但并不理想。欢迎大家有好的想法分享。