Angular 1.x下 select 的一个巨大的坑
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Angular 1.x下 select 的一个巨大的坑相关的知识,希望对你有一定的参考价值。
双向绑定这个特性有时让人又爱又恨
假设控制器
function($scope){
$scope.options = [{name:”alex”,id:232,…},{…},{…}…];
$scope.myModel = {name:”alex”,id:232};
}
<select ng-model=”myModel.id”>
<option value=””>—请选择—</option>
<option ng-repeat=”opt in options” value=”{{opt.id}}” >
{{opt.name}}
</option>
</select>
ok,这段看起来很寻常的代码会出现问题
inspect一下
?number:45?
多次调试发现不是程序写得有问题
这个是angular中select的一个缺陷
以下是官方说法
To bind the model to a non-string value, you can use one of the following strategies:
- the
ngOptions
directive (select
) - the
ngValue
directive, which allows arbitrary expressions to be option values (Example) - model $parsers / $formatters to convert the string value (Example)
然而我尝试了ngOptions时依然无效
最终解决方案:
app.directive(‘convertToNumber’, function () {
return {
require: ‘ngModel’,
link: function (scope, element, attrs, ngModel) {
ngModel.$parsers.push(function (val) {
return val != null ? parseInt(val, 10) : null;
});
ngModel.$formatters.push(function (val) {
return val != null ? ” + val : null;
});
}
};
});
以上是关于Angular 1.x下 select 的一个巨大的坑的主要内容,如果未能解决你的问题,请参考以下文章
在 Angular 中导入全局 css 文件会导致 Webpack 发出巨大的模块包
NativeScript Angular ListPicker 的行为类似于 `<select>`
Angular2 [selected] 设置默认值不起作用?